【发布时间】: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