Asynchronous 立即解决的可观察-相当于$q.when()
在做我的第一个Angular 2 CRUD练习时,我尝试重新使用我的编辑表单来添加新对象和编辑现有对象 我有一个不正确的代码:Asynchronous 立即解决的可观察-相当于$q.when(),asynchronous,angular,observable,Asynchronous,Angular,Observable,在做我的第一个Angular 2 CRUD练习时,我尝试重新使用我的编辑表单来添加新对象和编辑现有对象 我有一个不正确的代码: this._route.params.forEach((params: Params) => { let id = params['id']; if (id) { this._productService.getProduct(id) .subscribe( product =&g
this._route.params.forEach((params: Params) => {
let id = params['id'];
if (id) {
this._productService.getProduct(id)
.subscribe(
product => this.product = product,
error => this.errorMessage = <any>error
);
} else {
this.product = {
name: 'default name',
ean: '',
price: 0,
qty: 0,
imageUrl: '',
_id: ''
};
}
});
(<FormGroup>this.registerForm).setValue(this.product, {onlySelf: true});
this.\u route.params.forEach((params:params)=>{
设id=params['id'];
如果(id){
此.\u productService.getProduct(id)
.订阅(
product=>this.product=product,
error=>this.errorMessage=错误
);
}否则{
该产品={
名称:“默认名称”,
ean:“,
价格:0,,
数量:0,
imageUrl:“”,
_id:“”
};
}
});
(this.registerForm).setValue(this.product,{onlySelf:true});
。。。这也难怪不起作用——因为如果的一部分是同步的,那么另一部分是异步的
我想优化代码,并将静态默认对象模板转换为一个立即解析的可观察值-基本上相当于$q.when(myVar)
。我该怎么做呢?现在我知道应该是:
return Observable.of({
name: 'default name',
ean: '',
price: 0,
qty: 0,
imageUrl: '',
_id: ''
});