简体   繁体   中英

Angular not refreshing component after subscribe

My Angular Component the 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')
    });
  }
}

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

Template

  <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>

The subscribe event works but does not refresh my component to change the buttonText or isAuthenticated boolean. I get the console.log('ProductitemComponent_ngOnInit') The ProductItemComponent can be displayed on the page 10, 50 or 100 times. Everything is setup do I need to force a refresh, I do not see anywhere that say I should have to do that

Might be issue related to this line:

this.isAuthenticated = e != null;

Just try:

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

发现将 ProductList 组件设置为 ChangeDetectionStrategy.OnPush

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM