侦听服务变量从组件角度的变化 [英] listen to service variable change from component angular

查看:76
本文介绍了侦听服务变量从组件角度的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为变量和方法提供服务,该方法将数据带入该变量

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错误TypeError:无法读取属性订阅" 的未定义

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设为可观察的.这样,您可以在其中的值更改时收听它

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可观察到的自身.


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆