Angular 4 - 服務



本章將討論 Angular 4 中的服務。

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

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

C:\projectA4\Angular 4-app>ng g service myservice
installing service
   create src\app\myservice.service.spec.ts
   create src\app\myservice.service.ts
   WARNING Service is generated but not provided, it must be provided to be used

   C:\projectA4\Angular 4-app>

檔案如下建立在 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**。現在我們將返回新建立的 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 4 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 Comonent 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。在下一行,我們將變數的值更改為“**元件已建立**”。我們將在 **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
廣告