我在开发angular2 app时遇到了另一个问题。我有一个需要通过Web API调用的设置。我有一个依赖于该设置的管道。由于http.get的性质是异步的,在调用Web API完成时,有什么方法可以阻止管道加载吗?
示例:
import {Component, OnInit} from 'angular2/core'
import {myPipe} from './myPipe'
import {settingService} from './setting.service'
@Component({
template:'{{"setting.val1" | myPipe}}',
providers:[settingService],
pipes:[myPipe]
})
export class mainComponent implements OnInit{
constructor(private _myService:settingService){}
ngOnInit(){
this._myService.getSetting() //this needs to complete first before the pipe executes
}
}
如您所见,字符串settings.val1将通过管道进行转换。但是,在管道开始转换之前,需要先完成this._myService.getSetting()的调用。我的问题是如何在调用getSetting()之前阻止管道执行?
谢谢,
更新
SettingService代码如下:
export class SettingService{
constructor(private _http:http){}
public getSetting():void{
this._http.get('someAPI')
.map((result)=>{return result.toJSON()})
.subscribe((data:any)=>{localStorage.setItems("settings",json.stringify(data))})
}
}
所以基本上服务调用web api并将其存储在localStorage中。管道只需解析localStorage中的值并调用该对象。
表示如果字符串作为setting1.val1传入,则管道中的transform函数将为
transform(val,args){
let settings = json.parse(localStorage("settings"))
return eval("settings." + val); //in this instance, it will execute settings.setting.val1
}
答案 0 :(得分:1)
class MyPipe {
constructor(private settingService:SettingService) {}
transform(val,args){
return this.settingService.getSetting().then(_ => {
let settings = json.parse(localStorage("settings"))
return eval("settings." + val); //in this instance, it will execute settings.setting.val1
});
}
localStorage
实际上我会从管道中完全省略SettingService
,而只是与SettingService
进行通信,并将localStorage
更改为仅从服务器加载数据(如果它们未存储在{{1}}已经或类似(不了解您的要求)。