Angular 9: значение не обновляется при подписке на эмиттер - PullRequest
0 голосов
/ 07 апреля 2020

Я подписался на emitter и вижу вывод 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>

enter image description here

пожалуйста, дайте мне знать, если нужно больше деталей

код для обслуживания

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);
  }


}

Ответы [ 2 ]

2 голосов
/ 07 апреля 2020

Проблема в том, что ваш эмиттер излучает до того, как ваш шаблон будет готов. EventEmitter - это просто Subject, и он не генерируется снова, если вы подписались. Таким образом, EventEmitter технически должен использоваться только в angular Component или Directive в сочетании с и @Output

В вашем коде я не вижу, чтобы вы что-либо излучали в вашем orderDetailEmitter, но я думаю, что это то, что должно быть воспроизведено среди подписчиков. Вы должны использовать ReplaySubject для такой вещи:

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

  //...
}

Параметр 1 в качестве указывает, что следующий подписчик должен получить только последнее переданное значение потока.

1 голос
/ 08 апреля 2020

Конструктор стреляет рано. Переместите код инициализации из конструктора в ngOnInit () для вещей, от которых зависит ваш шаблон.

  1. Реализация OnInit в компоненте.
  2. Создайте функцию с именем ngOnInit () и поместите туда код подписки.

Пример:

export class MyComponent implements OnInit {

  // keep the constructor for dependency injection only
  constructor(
    private httpClient:HttpClient
  ) {}

  ngOnInit() {
     this.http.orderDetailEmitter.subscribe((response)=>{
        this.productNumber=response;

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

  ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...