[英]How we send data from one component to another sibling component in angular 8?
I am developing an CRUD operation.我正在开发一个 CRUD 操作。 While updating, on updateUser component I get data of user through service variable.
更新时,在 updateUser 组件上,我通过服务变量获取用户数据。 But when I refresh edit page the data of user is undefined.
但是当我刷新编辑页面时,用户的数据是未定义的。 Please suggest me a better solution of this.
请建议我一个更好的解决方案。
I do not want to call api of users on editpage.我不想在编辑页面上调用用户的 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)
}
}```
first of all, Angular is used to create SPA.首先,Angular用于创建SPA。 So you do not refresh page, but in case your application requires it, it is obvious that on refresh data from service will get undefined because when you refresh you complete application gets reloaded.
因此,您不刷新页面,但如果您的应用程序需要它,很明显,刷新服务中的数据将变得未定义,因为当您刷新时,您的完整应用程序会重新加载。
So, in your case, if you still need the value after refresh and do not want to make an API call you can use browser local storage.因此,在您的情况下,如果您仍然需要刷新后的值并且不想进行 API 调用,您可以使用浏览器本地存储。 With this you data will persist even after refresh but will be gone once the browser is closed.
有了这个,你的数据即使在刷新后也会保留,但一旦浏览器关闭就会消失。
Refer: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage for more detail and implementation of local store.参考: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage了解本地存储的更多细节和实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.