簡體   English   中英

angular html 在訂閱時不呈現

[英]angular html not rendering on subscribe

我在登錄按鈕單擊時執行此代碼:

login() {
console.log('inside login');
this.childComponent.refreshFromParent();  //subscribe greeting
this.app.authenticate(this.credentials, () => { //subjectGreeting.next()

this.childComponent 是另一個包含方法 refreshFromParent() 的組件

  refreshFromParent(): void{
    console.log('home component refresh from parent'); 
    this.subscriptionGreeting = this.app.resGreeting.subscribe(r => {
      console.log('inside greeting subscription');
      console.log(r);
      console.log(typeof r);
      console.log(typeof this.greeting);
      if(r){
        this.greeting.id = r.id;
        this.greeting.content = r.content;
        //console.log(r);
        //console.log(this.greeting);
      }
    });
  
  }

可以看出,refreshFromParent() 方法在 authenticate() 方法之前被調用,因此,訂閱是在 subject.next() 之前完成的。

以下是驗證代碼:

  authenticate(credentials, callback) {
    const headers = new HttpHeaders({ Authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
    });

    return this.http.get<Greeting>('http://localhost:8080/user', {headers},).subscribe(response => {
        console.log('Inside app service authenticate');
        if (response) {
            this.authenticated = true;
            console.log(response);
            this.subjectGreeting.next(response);
            this.subjectAuthenticated.next(true);
        } else {
            this.authenticated = false;
            this.subjectAuthenticated.next(false);
        }
        callback();
    });

  }

最后,如果 object id 不是空字符串,子組件的 html 會顯示問候語,如下所示:

<div *ngIf="greeting.id != ''">
    <p> The ID is {{ greeting.id }}</p>
    <p>The content is {{ greeting.content }}</p>
    <p>{{greeting}}</p>

但是,沒有呈現任何內容,這意味着 greeting.id 是空字符串。 以下是我的控制台日志: 在此處輸入圖像描述

EDIT1:以下是來自瀏覽器的 html 頁面快照: 在此處輸入圖像描述

請幫忙!

實際上,問題出在您的此代碼塊中。 我有更新,請使用這個:

refreshFromParent(): void{
    console.log('home component refresh from parent'); 
    this.subscriptionGreeting = this.app.resGreeting.subscribe(r => {
      console.log('inside greeting subscription');
      console.log(r);
      console.log(typeof r);
      console.log(typeof this.greeting);
      if(r){
        this.greeting = { ...r };        
        //console.log(r);
        //console.log(this.greeting);
      }
    });
  
  }

嘗試更改您視圖中的條件:

而不是<div *ngIf="greeting.id != ''">
試試<div *ngIf="greeting?.id != ''">
<div *ngIf="(greeting | async)?.id != ''">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM