EventSpinner组件订阅EventsService提供的图标。
@Component({
selector: 'event-spinner',
template: `
<div class="col-xs-5">
Test <i class="fa fa-2x" [ngClass]="{'fa-check': icon == 'ok', 'fa-spin': icon == 'loading', 'fa-spinner': icon == 'loading', 'fa-times': icon == 'error'}" id="spin"></i>
</div>
`
})
export class EventSpinner implements OnInit {
icon: string;
constructor(public eventsService: EventsService) {
}
ngOnInit(): void {
this.eventsService.icons.subscribe((icon) => {
let old = this.icon;
this.icon = icon;
console.log("this.icon = " + this.icon + " (was " + old + ")");
});
}
}
当使用@ angular / http.get状态的Web服务请求发生更改时,icons.next被调用(&#34;加载&#34; /&#34; ok&#34; /&#34;错误&#34;) 。但是当发生这种情况时,i标签的类不会更新。任何想法?
EventsService.ts
@Injectable()
export class EventsService {
icons: Subject<string> = new Subject<string>();
constructor(public http: Http) {
}
subscribe(): Observable<Event[]> {
let url = (<any>window).__ext.API_URL + 'event/view';
let obs;
return Observable
.create((o) => {
obs = o;
obs.next();
})
.flatMap(() => {
this.icons.next("loading");
console.log("executing request");
return this.http.get(url)
})
.retryWhen(error => {
this.icons.next("error");
return error.delay(3000);
})
.map((response: Response) => {
this.icons.next("ok");
console.log("response received");
setTimeout(() => {
console.log("pushing next");
obs.next();
}, 1000);
return (<any>response.json()).map(item => {
return item;
});
});
}
}
答案 0 :(得分:1)
这可能是由EventService
的实施引起的,或者可能是ngClass
的问题,但手动调用更改检测应解决此问题:
export class EventSpinner implements OnInit {
icon: string;
constructor(public eventsService: EventsService, private cdRef:ChangeDetectorRef) {
}
ngOnInit(): void {
this.eventsService.icons.subscribe((icon) => {
let old = this.icon;
this.icon = icon;
console.log("this.icon = " + this.icon + " (was " + old + ")");
this.cdRef.detectChanges();
});
}
}
答案 1 :(得分:0)
使用:
new Observable(...);
和
new BehaviorSubject(...);
而不是静态
X.create();
解决了我的所有问题。