Angular 2 - 将数据从服务传递到组件

Hap*_*der 2 angular

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

这就是我所拥有的:

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

然后我有一个服务:

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;
                }
            );

    }

}
Run Code Online (Sandbox Code Playgroud)

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

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

什么过程正确地返回这个?

Thi*_*ier 5

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

我会使用map运算符:

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

在组件中:

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

}