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

问题描述:

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

I have created a service that calls an api to get some data. I want to return this to the calling component.

这就是我所拥有的:

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数组中,则返回数据.如果不是,则返回false.

The idea is that I can call the method getKey('some-key') and if the key exists in the returned json array, the data is returned. If not, false is returned.

运行此命令时,我可以看到该对象已在服务中返回,但是没有返回到组件中,而是得到了未定义".

When this runs I can see the object is being returned in the service, however it is not being returned to the component, instead I get "undefined".

如何正确返回此结果?

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

Your problem is that your processing is asynchronous and you return within the callback not within the calling method.

我将为此使用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);
    });
}

}