Angular компонент не обновляется после подписки - PullRequest
1 голос
/ 04 марта 2020

Мой Angular Компонент userService

import { Component, OnInit, Input } from '@angular/core';
import { ProductItem } from 'src/app/service/product.service';
import { UserService } from 'src/app/service/user.service';
import { IUser } from 'src/app/service/firebase.service';

@Component({
  selector: 'shopping-productitem',
  templateUrl: './productitem.component.html',
  styleUrls: ['./productitem.component.css']
})
export class ProductitemComponent implements OnInit {

  @Input() productItem: ProductItem;

  isAuthenticated: boolean = true;
  buttonText: string = '';
  constructor(private _userService: UserService) { }

  ngOnInit(): void {
    this._userService.userObserve.subscribe((e : IUser) => {
      this.isAuthenticated = true;
      this.buttonText = 'Add';
      console.log('ProductitemComponent_constructor')
    });
  }
}

Мой UserService

  export class UserService {

  constructor() { }

  private userSource = new Subject<IUser>();
  userObserve = this.userSource.asObservable();

  public OnAuthStateChanged(): void {
    console.log('FirebaseService_OnAuthStateChanged');
    const app = this._getApp();
    app.auth().onAuthStateChanged( (user: IUser) => {
      this.userSource.next(user);
    });
  };
}

Шаблон

  <div class="card" style="width: 18rem;">
    <div class="card-body">
      <img src={{productItem.LargeImageURL}} class="card-img-top" style="width: 200px; height: 200px;" alt={{productItem.ProductTitle}}>
      <h5 class="card-title">{{productItem.ProductTitle}}</h5>
      <h6 class="card-subtitle mb-2 text-muted">{{productItem.SKU}}</h6>
      <p class="card-text">{{productItem.ProductDescription}}</p>
      <p class="card-text">{{productItem.Price | currency}}</p>
      <button type="button" class="btn btn-primary"  [attr.disabled]="!isAuthenticated ? '' : null">{{buttonText}} </button>
    </div>
  </div>

Событие подписки работает, но не обновляется sh Мой компонент для изменения ButtonText или isAuthenticated логического. Я получаю console.log('ProductitemComponent_ngOnInit') ProductItemComponent может отображаться на странице 10, 50 или 100 раз. Все настроено, мне нужно заставить refre sh, я не вижу нигде, чтобы сказать, что я должен сделать это

Ответы [ 2 ]

0 голосов
/ 05 марта 2020

Понял, что для компонента ProductList установлено значение ChangeDetectionStrategy.OnPu sh

0 голосов
/ 04 марта 2020

Может быть проблема, связанная с этой строкой:

this.isAuthenticated = e != null;

Просто попробуйте:

this._userService.userObserve.subscribe((e) => {
  console.log('ProductitemComponent_ngOnInit')
  if(e) {
    this.isAuthenticated = e;
    this.buttonText = 'Add';
  }
});
...