我有不同的问题。
我将服务中的数据检索到变量中,但加载后此数据不会显示在屏幕上(我使用Subscription进行此操作)。单击带有功能getMessages(){ console.log(this.messages);}
你能解释一下原因吗?
import {Component, NgZone, OnInit} from '@angular/core';
import {GmailApiService} from "../google/api/gmailApi.service";
import {Subscription} from "rxjs/Rx";
@Component({
selector: 'gmail-app',
templateUrl: '/app/gmail/gmail.component.html'
})
export class GmailComponent implements OnInit{
public messages: Array<string>;
subscription:Subscription;
constructor(private gmailApi: GmailApiService){
}
ngOnInit() {
this.gmailApi.checkAuthAuto('from:(xyz@zyx.com) OR to:(azx@saa.com)');
this.subscription = this.gmailApi.openMessages$
.subscribe(messages => this.messages = messages);
}
getMessages(){
console.log(this.messages);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
组件文件:
<template [ngIf]="messages">
Messages:
<h1 *ngFor="let message of messages">**{{message?.id}}**</h1>
</template>
<button id="button-get" (click)="getMessages(event)">
getMessages
</button>
我为我的问题找到了解决方案,我在订阅中添加了区域,现在它正常工作。下面我在h
之后提出我的部分代码constructor(private zone:NgZone, private gmailApi: GmailApiService){
}
ngOnInit() {
this.gmailApi.checkAuthAuto('from:(xyz@zyx.com) OR to:(azx@saa.com)');
this.subscription = this.gmailApi.openMessages$
.subscribe(messages => {
this.zone.run(() => {
this.messages = messages;
});
});
}
答案 0 :(得分:2)
我认为它可能与生命周期钩子有关。请参阅:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
我不确定但是你应该实现doCheck和订阅调用ngDoCheck方法吗?像这样:
<ul>
<li>ITEM 1</li>
<li>ITEM 2</li>
<li>ITEM 3</li>
<li>ITEM 4</li>
<li>ITEM 5</li>
<li>ITEM 6</li>
<li>ITEM 7</li>
<li>ITEM 8</li>
<li>ITEM 9</li>
<li>ITEM 10</li>
<li>ITEM 11</li>
<li>ITEM 12</li>
<li>ITEM 13</li>
<li>ITEM 14</li>
<li>ITEM 15</li>
<li>ITEM 16</li>
<li>ITEM 17</li>
<li>ITEM 18</li>
<li>ITEM 19</li>
<li>ITEM 20</li>
<li>ITEM 21</li>
</ul>