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