【发布时间】:2016-04-14 16:06:01
【问题描述】:
我在开发 angular2 应用程序的架构上遇到了另一个问题。我有一个需要通过 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(val,args){
let settings = json.parse(localStorage("settings"))
return eval("settings." + val); //in this instance, it will execute settings.setting.val1
}
【问题讨论】:
-
如果
this._myService.getSetting()返回一个 Observable 或一个 Promise。你可以使用AsyncPipe,这就是它的用途。 -
@Abdulrahman getSetting 确实返回 observable。为了简洁起见,我只是省略了。当您说使用 asyncPipe 时,我该如何使用它?我是否只是将它与我的自定义链接?
-
如果您在问题中包含
getSetting代码会更好。但是,假设您有一个可观察的,它将是这样的:settings | async | myPipe。 -
@Abdulrahman 实际上我没有返回 observable。该函数实际上是调用 http.get 并将结果存储在 localStorage 中。您可以检查上面的更新代码
标签: angular