![](/img/trans.png)
[英]How do I send data from a Component to another Component in Angular?
[英]How we send data from one component to another sibling component in angular 8?
我正在開發一個 CRUD 操作。 更新時,在 updateUser 組件上,我通過服務變量獲取用戶數據。 但是當我刷新編輯頁面時,用戶的數據是未定義的。 請建議我一個更好的解決方案。
我不想在編輯頁面上調用用戶的 api。
this.route.params.subscribe(params => {
if (Object.keys(params).length > 0) {
this.editId = (Object.values(params))[0];
}
})
if(this.traineeData) {
this.traineeData = this.traineeService.traineeData; // here I am getting data, but on refreshing it becomes undefined
} else {
this.traineeData = this.traineeService.traineeData;
}
console.log(this.traineeData)
}
export class UserService {
traineeData: any;
constructor(private http: HttpClient) { }
getTrainee() {
return new Promise((resolve,reject) => {
this.http.get('url').subscribe(
res => resolve(res),
err => reject(err));
})
}
provideTraineeDataForEdit(data) {
this.traineeData = data
console.log(this.traineeData)
}
}```
首先,Angular用於創建SPA。 因此,您不刷新頁面,但如果您的應用程序需要它,很明顯,刷新服務中的數據將變得未定義,因為當您刷新時,您的完整應用程序會重新加載。
因此,在您的情況下,如果您仍然需要刷新后的值並且不想進行 API 調用,您可以使用瀏覽器本地存儲。 有了這個,你的數據即使在刷新后也會保留,但一旦瀏覽器關閉就會消失。
參考: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage了解本地存儲的更多細節和實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.