Angular 2 - passing data from service to component

2020-06-27 04:04发布

问题:

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

This is what I have:

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

Then I have a service:

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

    }

}

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".

Whats the process to return this correctly?

回答1:

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

I would use the map operator for this:

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

and in the component:

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

}



标签: angular