【问题标题】:Angular 2 - passing data from service to componentAngular 2 - 将数据从服务传递到组件
【发布时间】:2016-04-21 16:20:40
【问题描述】:

我创建了一个调用 api 来获取一些数据的服务。我想将此返回给调用组件。

这就是我所拥有的:

SomeComponent() {
 someData = string;
 constructor(
        private _configService: SomeService
    )
    {
       var value = this._configService.getKey('some-key');
       console.log(value);
    }
}

那我有一个服务:

export class ConfigService {

    response:any;

    constructor(private _http:Http) {}

    getConfig(): Observable<any>
    {
        return this._http.get('src/config/config.json')
            .map(response => response.json()).publishLast().refCount();
    }

    getKey(key:string) {
        this.getConfig()
            .subscribe(
                data => {

                    if (data[key] != 'undefined')
                    {
                        return data[key]
                    } else {
                        return false;
                    }

                },
                error => {
                    return false;
                }
            );

    }

}

想法是我可以调用getKey('some-key')方法,如果返回的json数组中存在key,则返回数据。如果不是,则返回 false。

当它运行时,我可以看到该对象正在服务中返回,但是它没有返回到组件,而是我得到“未定义”。

正确返回这个的过程是什么?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您的问题是您的处理是异步的,并且您在回调中而不是在调用方法中返回。

    我会为此使用map 运算符:

    getKey(key:string) {
        return this.getConfig().map(data => {
          if (data[key] != 'undefined') {
            return data[key];
          } else {
            return false;
          }
        );
    }
    

    在组件中:

    SomeComponent() {
      someData = string;
      constructor(
        private _configService: SomeService
      ) {
        this._configService.getKey('some-key').subscribe(value => {
          console.log(value);
        });
    }
    

    }

    【讨论】:

    • 好的 - 试一试,现在出现这个错误:TypeError: Cannot read property 'subscribe' of undefined
    • 哦,我错过了getKey 方法中的return。对不起!我相应地更新了我的答案......
    猜你喜欢
    • 2019-05-26
    • 2018-03-29
    • 2017-07-21
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2017-10-19
    • 2018-06-30
    • 2017-11-25
    相关资源
    最近更新 更多