加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2全局变量可观察

发布时间:2020-12-17 10:19:50 所属栏目:安全 来源:网络整理
导读:我对angular2很新,我有点卡在某事上. 我创建了一个全局settings.service.此服务从API获取设置,并使用收集的数据填充设置模型. 服务: public settings : settingsModel;constructor(public http: Http){ this.setSettings() .subscribe( (data) = { this.set
我对angular2很新,我有点卡在某事上.

我创建了一个全局settings.service.此服务从API获取设置,并使用收集的数据填充设置模型.

服务:

public settings : settingsModel;

constructor(public http: Http){ 
     this.setSettings()
         .subscribe(
             (data) => {
                  this.settings = data
             });
  }

setSettings() : Observable<any>{
   return : this.http.get('/settings')
            .map(response =>  response.json());
}

getSettings(){
     return this.settings;
}

这工作正常,我在.map中测试返回数据时正确设置了设置

但是当我尝试从需要此数据的组件调用GetSettings时,它返回空.该服务在引导程序中定义.

我是否需要使’settings’变量可观察?任何帮助将非常感谢!

TNX!

我将使用do运算符将缓存实现到您的服务中:
private settings : settingsModel;

constructor(public http: Http){ 
  this.settingsObservable = this.http.get('/settings')
        .map(response => response.json())
        .do(settings => {
          this.settings = settings;
        }).share();
}

getSettings() {
  if (this.settings) {
    return Observable.of(this.settings);
  } else {
    return this.settingsObservable;
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读