Angular Subscribe()方法
我們將介紹 Angular 的 subscribe() 方法並在我們的應用程式中使用它。
Angular Subscribe() 方法
    
Subscribe() 是 Angular 中將 observer 連線到 observable 事件的方法。每當對這些 observable 進行任何更改時,都會執行程式碼並使用 subscribe 方法觀察結果或更改。Subscribe() 是 rxjs 庫中的一個方法,由 Angular 內部使用。
時事通訊是現在網站中最常見的部分;讓我們把它們想象成一個可觀察的事件,而我們作為觀察者。當我們在任何網站上輸入我們的電子郵件到時事通訊表格時,我們訂閱了一個可觀察的事件。每當該網站釋出任何新的時事通訊時,我們都會在我們的電子郵件中收到它,直到我們取消訂閱該事件。
同樣,如果我們想要在 Angular 應用程式上觀察任何函式,我們就會訂閱該函式。每當對該函式進行任何更改時,我們都可以使用 subscribe() 方法檢視更改。
Subscribe() 接受三個方法作為引數:next、error 和 complete。
- 使用 
next方法,我們可以傳遞 observable 發出的每個值。 - 使用 
error方法,我們可以傳遞流中某處發生的任何錯誤。 - 使用 
complete方法,我們可以在整個可觀察事件完成後傳遞值。 
讓我們通過一個例子來詳細瞭解 subscribe()。首先,我們將建立一個名為 subscribe.service.ts 的新服務檔案,我們將在其中建立 assignValue() 函式,該函式將使用 next 方法將值傳遞給觀察者。
我們在 subsribe.service.ts 中的程式碼將如下所示。
# angular
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root',
})
export class SubscribeService {
  assignValue() {
    const SubscribeObservable = new Observable((observer) => {
      observer.next('Angular');
    });
    return SubscribeObservable;
  }
}
    
接下來,我們將在 app.module.ts 中匯入此服務,並在@NgModule 中將其定義為提供程式。
# angular
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { SubscribeService } from './subscribe.service';
@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent],
  providers: [SubscribeService],
})
export class AppModule {}
在 app.component.ts 檔案中的下一步中,我們將為我們的服務建立一個建構函式和一個將從觀察者那裡獲取值的函式。並且不要忘記在 app.component.ts 檔案中匯入我們的服務。
# angular
import { Component, VERSION } from '@angular/core';
import { SubscribeService } from './subscribe.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  constructor(private SubscribeService: SubscribeService) {}
  ngClick() {
    this.SubscribeService.assignValue().subscribe((result) => {
      console.log(result);
    });
  }
}
現在,我們將在 app.component.html 中建立一個模板。
# angular
<hello name="{{ name }}"></hello>
<button (click)="ngClick()">Click Here to see result</button>
    
輸出:

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn