首页 > 解决方案 > Angular 9:订阅发射器时值未更新

问题描述

我订阅了发射器,我可以在控制台中看到 this.productNumber 的输出。但它在 html 文件中不可见。我像{{productNumber}} 在 html 文件中一样使用它。

constructor(private http : HttpClientService) {
        this.http.orderDetailEmitter.subscribe((response)=>{
          this.productNumber=response;

        console.log("productNumber"+this.productNumber);
        });
       }

HTML 文件

<div>
          <div class="mat-display-1">you have {{productNumber}} product</div>
          <mat-form-field floatLabel="never" appearance="legacy" color="accent">


              <mat-label> Name</mat-label>

              <input matInput required>
              <mat-hint align="end">min 5 characters</mat-hint>

            </mat-form-field>
        </div>

在此处输入图像描述

如果需要更多详细信息,请告诉我

服务代码

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { EventEmitter } from '@angular/core';

export class Employee{
  constructor(
    public empId:string,
    public name:string,
    public designation:string,
    public salary:string,
    public isEditable : boolean
  ) {}
}

@Injectable({
  providedIn: 'root'
})
export class HttpClientService {
  orderDetailEmitter = new EventEmitter<number>();


  constructor(
    private httpClient:HttpClient
  ) {

     }

     getEmployees()
  {

    return this.httpClient.get<Employee[]>('http://localhost:8081/fetchEmployees');
  }

  public deleteEmployee(employee) {
    return this.httpClient.delete<Employee>("http://localhost:8081/deleteEmployee" + "/"+ employee.emailid);
  }

  public createEmployee(employee) {
    return this.httpClient.post<Employee>("http://localhost:8081/employees", employee);
  }

  public updateEmployee(employee){
    return this.httpClient.post<Employee>("http://localhost:8081/updateEmployee", employee);
  }

  public createUser(user){
    return this.httpClient.post("http://localhost:8081/registration",user);
  }


}

标签: angularangular9angular-event-emitter

解决方案


问题是您的发射器在您的模板准备好之前发射。如果您订阅,EventEmitter则基本上只是一个Subject并且不会再次发出。因此,从EventEmitter技术上讲,应该仅以角度ComponentDirective与和结合使用@Output

在您的代码中,我看不到您在 . 中发出任何内容orderDetailEmitter,但我想这是需要在订阅者之间重播的内容。你应该使用 aReplaySubject这样的事情:

export class HttpClientService {
  readonly orderDetailEmitter = new ReplaySubject<number>(1);

  //...
}

1as 参数指示下一个订阅者应该只接收流的最后发出的值。


推荐阅读