从组件角度监听服务变量变化 [英] listen to service variable change from component angular
问题描述
我有变量服务和将数据带入该变量的方法
I have service with variable and method that brings data to that variable
export class UserService {
userDetails;
getUserProfile(){
return this.http.get(this.BaseURI+'/UserProfile').subscribe(
res=>{
this.userDetails=res;
// console.log(res);
},
err=>{
console.log(err);
}
);
}
现在我想在变量更改时从组件中检查并读取它.我该怎么做?
now I want to check from component when the variable changes and read it. How can I do that ?
更新.
export class UserService {
userDetails;
getUserProfile(){
this.http.get(this.BaseURI+'/UserProfile').subscribe(
res=>{
this.userDetails=res;
},
err=>{
console.log(err);
}
)
}
在组件中我有这个:
ngOnInit() {
this.service.userDetails.subscribe((userDetails) =>this.userDetails=userDetails)
}
现在当我运行应用程序时,组件中出现错误:
Now When I run the app I get error in component:
AppComponent.html:2 错误类型错误:无法读取属性订阅"未定义的
AppComponent.html:2 ERROR TypeError: Cannot read property 'subscribe' of undefined
推荐答案
相信你的get请求完成后基本上需要组件中的数据了.
I believe you basically need the data in the component when your get request is completed.
解决方案 1:考虑将 userDetails
设为 Observable,.这样你就可以在其中的值发生变化时收听它
Solution 1: Consider making userDetails
as an Observable, . This way you could listen to it when the value in it changes
export class UserService {
private _userDetails: Subject<any> = new Subject<any>(); // consider putting the actual type of the data you will receive
public userDetailsObs = this._userDetails.asObservable();
getUserProfile(){
return this.http.get(this.BaseURI+'/UserProfile').subscribe(
res=>{
this._userDetails.next(res)
// console.log(res);
},
err=>{
console.log(err);
}
);
}
}
在您的组件内部
constructor(private _userService: UserService) {}
ngOnInit() {
this._userService.userDetailsObs.subscribe((userDetails) => {
console.log(userDetails)
})
}
<小时>
解决方案 2. 考虑只返回 HTTP observable 本身.
Solution 2. Consider just returning the HTTP observable itself.
getUserProfile(){
return this.http.get(this.BaseURI+'/UserProfile');
}
在您的组件内部
constructor(private _userService: UserService) {}
ngOnInit() {
this._userService.getUserProfile.subscribe((userDetails) => {
console.log(userDetails)
})
}
这篇关于从组件角度监听服务变量变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!