Angular 2订阅返回空对象
我无法在我的模板中呈现数据,因为property:product = {}是 返回空对象。Angular 2订阅返回空对象
ProductComponent.ts --->
{
category$;
product={};
id;
constructor(
private router:Router,
private route:ActivatedRoute,
private categoryService:CategoryService,
private productService:ProductService)
{
this.category$= categoryService.getCategories();
this.id=this.route.snapshot.paramMap.get('id');
if(this.id)
this.productService.getProduct(this.id).take(1)
.subscribe(p=>this.product=p);
console.log(this.product)
}
this.product
被示出为空。虽然当我在订阅内登录“p”时, 正在返回空对象。但只是不在订阅之外。 我无法获取模板上的产品数据也是因为此空的 对象。
模板--->
<label for="title">Title</label>
<input #title="ngModel" [(ngModel)]="product.title" name="title"
id="title" type="text" class="form-control" required>
<div class="alert alert-danger" *ngIf="title.touched && title.invalid">
Title is required
</div>
HELP!
下面是我ProductService
import { AngularFireDatabase } from 'angularfire2/database';
import { Injectable } from '@angular/core';
@Injectable()
export class ProductService {
constructor(private db: AngularFireDatabase) { }
create(product){
return this.db.list('/products').push(product);
}
update(productId, product)
{
return this.db.object('/products/' + productId).update(product);
}
deleteProduct(productId){
this.db.object('/products/' + productId).remove();
}
getAll(){
return this.db.list('/products');
}
getProduct(id){
return this.db.list('/products/' + id);
}
}
尝试这样的:
打印内部控制台的订阅方法
if(this.id) {
this.productService.getProduct(this.id).take(1)
.subscribe(p => {
this.product = p
console.log('this.product', this.product);
});
}
this.product按照您的建议设置为订购内的产品对象。但是,当此产品在外部使用时,它是空的。此外,执行的语句顺序如下: Angular正在开发模式下运行。调用enableProdMode()以启用生产模式。 product-form.component.ts:30 {} product-form.component.ts:28 this.product(4)[{...},{...},{...},{...}] – Chaitanya
setTimeout订阅方法:像setTimeout(()=> { console.log('this.product',this.productt); },1000) – Chandru
检查此答案https://stackoverflow.com/questions/46860230/unable-预订数据到变量?希望它会有帮助 – Chandru
你必须调试您在为您服务'getProduct实施的方法( this.id)'。分享该方法的代码。或者你的服务的完整代码 – HDJEMAI
如果你使用大括号,会发生什么?:if(){// code here}'你能从'ProductService'共享一个包含'getProduct()'方法的代码片段吗? – stealththeninja