angular - 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);
}
}
解决方案
问题是您的发射器在您的模板准备好之前发射。如果您订阅,EventEmitter
则基本上只是一个Subject
并且不会再次发出。因此,从EventEmitter
技术上讲,应该仅以角度Component
或Directive
与和结合使用@Output
在您的代码中,我看不到您在 . 中发出任何内容orderDetailEmitter
,但我想这是需要在订阅者之间重播的内容。你应该使用 aReplaySubject
这样的事情:
export class HttpClientService {
readonly orderDetailEmitter = new ReplaySubject<number>(1);
//...
}
1
as 参数指示下一个订阅者应该只接收流的最后发出的值。
推荐阅读
- python - Colab 上没有名为“tensorflow.compat.v2”的模块
- algorithm - 距离和时基计算
- node.js - 电子商务应用使用 Node.js 和 MySQL Sequelize 生成 pdf 发票
- vbscript - 在 VBScript/JScript 中为控制台应用程序编写代理启动器
- mysql - MYSQL 插入缺少日期的行
- java - Spring Boot oauth2 配置中的多个客户端凭据-动态使用
- javascript - 编辑表单在提交时不会更改 - 仅在硬刷新时
- python - 运行时错误:CUDA 在训练结束时内存不足并且不保存模型;火炬
- binary - 计算机中的二进制运算
- flutter - 如何为大于 360 度的扫掠角应用扫掠梯度