Angular 6 - 服務



本章我們將討論 Angular 6 中的服務。

我們可能會遇到這樣的情況:需要一些程式碼在頁面的任何地方都能使用。這可能是需要跨元件共享的資料連線等。服務幫助我們實現這一點。使用服務,我們可以訪問整個專案中其他元件的 方法和屬性。

要建立服務,我們需要使用命令列。相應的命令是:

C:\projectA6\Angular6App>ng g service myservice
CREATE src/app/myservice.service.spec.ts (392 bytes)
CREATE src/app/myservice.service.ts (138 bytes)

檔案建立在 app 資料夾中,如下所示:

Files In App Folder

以下是底部建立的檔案 - **myservice.service.specs.ts** 和 **myservice.service.ts**。

myservice.service.ts

import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
   constructor() { }
}

這裡,Injectable 模組從 **@angular/core** 匯入。它包含 **@Injectable** 方法和一個名為 **MyserviceService** 的類。我們將在該類中建立我們的服務函式。

在建立新服務之前,我們需要在主父元件 **app.module.ts** 中包含已建立的服務。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
   declarations: [
      SqrtPipe,
      AppComponent,
      NewCmpComponent,
      ChangeTextDirective
   ],
   imports: [
      BrowserModule,
      RouterModule.forRoot([
         {
            path: 'new-cmp',
            component: NewCmpComponent
         }
      ])
   ],
   providers: [MyserviceService],
   bootstrap: [AppComponent]
})
export class AppModule { }

我們已經使用類名匯入了服務,並在 providers 中使用了相同的類。現在讓我們切換回服務類並建立一個服務函式。

在服務類中,我們將建立一個函式來顯示今天的日期。我們可以在主父元件 **app.component.ts** 中使用此函式,也可以在上章中建立的新元件 **new-cmp.component.ts** 中使用。

現在讓我們看看該函式在服務中的樣子以及如何在元件中使用它。

import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
   constructor() { }
   showTodayDate() {
      let ndate = new Date();
      return ndate;
   }
}

在上面的服務檔案中,我們建立了一個函式 **showTodayDate**。現在我們將返回建立的 new Date()。讓我們看看如何在元件類中訪問此函式。

app.component.ts

import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 6 Project!';
   todaydate;
   constructor(private myservice: MyserviceService) {}
   ngOnInit() {
      this.todaydate = this.myservice.showTodayDate();
   }
}

**ngOnInit** 函式在建立的任何元件中預設都會被呼叫。日期如上所示從服務中獲取。要獲取服務的更多詳細資訊,我們需要首先在元件 **ts** 檔案中包含該服務。

我們將在 **.html** 檔案中顯示日期,如下所示:

{{todaydate}}
<app-new-cmp></app-new-cmp> 
// data to be displayed to user from the new component class.

現在讓我們看看如何在建立的新元件中使用該服務。

import { Component, OnInit } from '@angular/core';
import { MyserviceService } from './../myservice.service';
@Component({
   selector: 'app-new-cmp',
   templateUrl: './new-cmp.component.html',
   styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
   todaydate;
   newcomponent = "Entered in new component created";
   constructor(private myservice: MyserviceService) {}
   ngOnInit() {
      this.todaydate = this.myservice.showTodayDate();
   }
}

在我們建立的新元件中,我們需要首先匯入我們想要的服務並訪問其方法和屬性。請參見突出顯示的程式碼。todaydate 在元件 html 中顯示如下:

<p>
   {{newcomponent}}
</p>
<p>
   Today's Date : {{todaydate}}
</p>

新元件的選擇器用於 **app.component.html** 檔案中。上面 html 檔案的內容將在瀏覽器中顯示如下:

Output New Component Created

如果更改任何元件中服務的屬性,則其他元件中的屬性也會更改。現在讓我們看看這是如何工作的。

我們將在服務中定義一個變數,並在父元件和新元件中使用它。我們將在父元件中再次更改屬性,並檢視在新元件中是否也更改了。

在 **myservice.service.ts** 中,我們建立了一個屬性並在其他父元件和新元件中使用了它。

import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
   serviceproperty = "Service Created";
   constructor() { }
   showTodayDate() {
      let ndate = new Date();
      return ndate;
   }
}

現在讓我們在其他元件中使用 **serviceproperty** 變數。在 **app.component.ts** 中,我們正在訪問該變數,如下所示:

import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 4 Project!';
   todaydate;
   componentproperty;
   constructor(private myservice: MyserviceService) {}
   ngOnInit() {
      this.todaydate = this.myservice.showTodayDate();
      console.log(this.myservice.serviceproperty);
      this.myservice.serviceproperty = "component created"; // value is changed.
      this.componentproperty = this.myservice.serviceproperty;
   }
}

我們現在將獲取變數並處理 console.log。在下一行,我們將變數的值更改為 **“component created”**。我們將在 **new-cmp.component.ts** 中執行相同的操作。

import { Component, OnInit } from '@angular/core';
import { MyserviceService } from './../myservice.service';
@Component({
   selector: 'app-new-cmp',
   templateUrl: './new-cmp.component.html',
   styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
   todaydate;
   newcomponentproperty;
   newcomponent = "Entered in newcomponent";
   constructor(private myservice: MyserviceService) {}
   ngOnInit() {
      this.todaydate = this.myservice.showTodayDate();
      this.newcomponentproperty = this.myservice.serviceproperty;
   }
}

在上面的元件中,我們沒有更改任何內容,而是直接將屬性賦值給元件屬性。

現在,當您在瀏覽器中執行它時,服務屬性將被更改,因為它的值已在 **app.component.ts** 中更改,並且對於 **new-cmp.component.ts** 將顯示相同的值。

還要檢查更改之前控制檯中的值。

Console Output
廣告
© . All rights reserved.