[英]How to assign global variable from subscribe() function and update the view
I am doing the task and I have a problem I can't assign value to global to be seen in the view in angular8.我正在做这项任务,但我有一个问题,我无法将值分配给 global 以便在 angular8 的视图中看到。 I know what is asynchronous but how to assign the value and update the view.
我知道什么是异步的,但是如何分配值和更新视图。
post-details.component.ts post-details.component.ts
export class PostDetailsComponent implements OnInit {
indexOfPost;
titles=[];
subscription: Subscription;
renderPost:boolean=false;
constructor(private activatedRoute:ActivatedRoute,private getSharedTitles:ShareInfoTitleService,private detectChanges: ChangeDetectorRef) {
this.subscription = this.getSharedTitles.getMessage().subscribe((title)=>{
this.titles=title.titles;
this.renderPost=true;
this.detectChanges.markForCheck();
});
}
ngOnInit() {
this.indexOfPost=this.activatedRoute.snapshot.paramMap.get("id");
}
}
post-details.component.html post-details.component.html
<p *ngIf="renderPost">works</p>
It does not work.这没用。 My aim is to show the titles in post-details.component.html.
我的目标是在 post-details.component.html 中显示标题。 I'll be grateful for the tips.Regards
我会很感激这些提示。问候
You can use async pipe which unsubscribes auto-magically.您可以使用自动取消订阅的异步 pipe 。
export class PostDetailsComponent implements OnInit {
indexOfPost;
titles: Observable<any> = this.getSharedTitles.getMessage();
constructor(private activatedRoute:ActivatedRoute,private getSharedTitles:ShareInfoTitleService,private detectChanges: ChangeDetectorRef) {
}
ngOnInit() {
this.indexOfPost=this.activatedRoute.snapshot.paramMap.get("id");
}
}
in template在模板中
<p *ngIf="(titles | async)">works</p>
There is no need to write too much for a simple task.没有必要为一个简单的任务写太多。 Just explore async pipe and it will automatically subscribe and unsubscribe.
只需探索异步pipe,它就会自动订阅和取消订阅。
export class PostDetailsComponent implements OnInit {
message$ = this.getSharedTitles.getMessage();
constructor(private activatedRoute:ActivatedRoute,private getSharedTitles:ShareInfoTitleService) {
}
ngOnInit() {
this.indexOfPost=this.activatedRoute.snapshot.paramMap.get("id");
}
}
In template在模板中
<p *ngIf="( message$ | async) as message">{{message.title}}</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.