[英]How to pass a value from ngOnInit to function
我想知道如何將 ngOnInit 的值傳遞給同一組件的 function 。
這是我的例子。 我從 API 獲取數據,以顯示我的頁面的上下文。 稍后當我單擊按鈕時,我想使用該數據,但在 console.log 中我沒有定義。 既然數據已經加載並顯示在我的頁面上,那是怎么回事。
...
clientId1;
clientId2;
clientNote;
errorMsg;
ngOnInit() {
this.clientId1 = this.route.parent.snapshot.paramMap.get('userId1');
this.clientId2 = this.getMethodClientId2();
}
getMethodClientId2(): void {
this.userService.getUser().subscribe(
(data) => {
this.clientNote = data.ClientNotes;
},
(error) => (this.errorMsg = error)
);
}
postMethodOnClick() {
console.log(this.clientId1);
console.log(this.clientId2);
}
...
這里有多個問題。
變量clientNote
被異步賦值。 因此,如果您要訪問訂閱之外的數據,您將無法確定數據是否已分配。
clientId2
變量不包含可能的客戶 ID,它目前什么也不包含。 從您的 function 的名稱來看,我相信您正在嘗試這樣做
ngOnInit() {
this.clientId1 = this.route.parent.snapshot.paramMap.get('userId1');
this.getMethodClientId2(); // <-- don't assign here, you aren't returning anything from the asynchronous function
}
getMethodClientId2(): void {
this.userService.getUser().subscribe(
(data) => {
this.clientNote = data.ClientNotes;
this.clientId2 = data.ClientId; // <-- I assume the property is called `ClientId`.
},
(error) => (this.errorMsg = error)
);
}
同樣,變量this.clientId2
是異步分配的,因此如果您在分配值之前調用 function postMethodOnClick()
,控制台日志仍然是undefined
。
有關如何訪問異步數據的更多信息,請參見此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.