![](/img/trans.png)
[英]Why am i getting undefined when accessing a closure variable in ReactJS
[英]Why I am getting empty BehaviorSubject when accessing by url
我有這樣的問題,我正在制作依賴於 angular8 中的博客系統的演示 web 頁面。 問題發生在那里:
當我使用 web 鏈接路由到展開的指定帖子時,它可以工作。 但是當我直接使用 /post-details/3 時,它不會。
post.component.ts
postDetailsClick(i){
this.getSharedBodies.subject.next(this.body); //setting BehaviorSubject
this.getSharedTitles.subject.next(this.titles);
this.router.navigate(['/post-details', i]);
}
post.component.html:
<mat-grid-list cols="3" rowHeight="150px">
<mat-grid-tile
*ngFor="let post of showPosts; let i = index"
[colspan]="post.cols"
[rowspan]="post.rows"
[style.background]="post.color">
{{post.text}}
<p><button (click)="postDetailsClick(i)" >Try it</button></p>
<br>
</mat-grid-tile>
</mat-grid-list>
post-details.component.html
export class PostDetailsComponent implements OnInit {
indexOfPost;
titles;
// bodies = [];
subscription: Subscription;
renderPost:boolean=false;
constructor(private activatedRoute:ActivatedRoute,private getSharedTitles:ShareInfoTitleService,private getSharedBodies: ShareInfoBodyService) {}
ngOnInit() {
this.indexOfPost=this.activatedRoute.snapshot.paramMap.get("id");
console.log(this.getSharedTitles.subject.asObservable());
}
}
行:console.log(this.getSharedTitles.subject.asObservable()); 當 url 直接訪問時,返回 null 可觀察的。 但是當單擊按鈕時,它可以正常工作。
export class ShareInfoTitleService {
subject = new BehaviorSubject<any>(null);
constructor() { }
sendMessage(message: any[]) {
this.subject.next({ titles: message });
}
clearMessages() {
this.subject.next(null);
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
問題是您僅在單擊時為 BehaviorSubject 提供值,因此當您通過鏈接輸入組件時,BS 中的最后一個數據可能是 null。 您必須在組件開始時提供一些數據才能獲取它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.