属性在组件中未定义,由 ngOnInit() 之外的订阅获取方法定义



当我控制台记录选定的属性时,我在评论中提到ngOnInit它确实控制台了对象,但是在这个块之外,当我控制台这个属性时它是未定义的。 可以帮忙如何让它工作吗..或任何其他解决方案

import { Product } from './../../Models/ProductModel';
import { Component, OnInit } from '@angular/core';
// import { Subscription } from "rxjs/Rx";
import 'rxjs';
import { Router, ActivatedRoute } from '@angular/router';
import { ProductService } from 'app/products/product.service';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html',
styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
public selectedProduct: Product;
private productIndex: string;
// private subscription: Subscription;
constructor(private router: Router,
private route: ActivatedRoute,
private PService: ProductService) { }
ngOnInit() {
this.route.params.subscribe(
(params: any) => {
this.productIndex = params['id'];
}
);

this.PService.getProduct(this.productIndex).subscribe((data: any) =>{
// return the object
console.log(data.product)
return this.selectedProduct = data.product,
//output the here object
console.log(this.selectedProduct);
}
);
// output undefined 
console.log(this.selectedProduct);

}



this is the getProduct method in my service
getProduct(id:string){
const headers = new Headers({ 'Content-Type': 'application/json' });
return this.http.get('http://localhost:3000/products/'+id, { headers : headers})
.map((response: Response) => response.json())
.catch( (error: any) =>
{
this.ErS.getError(error.json());
return Observable.throw(error);
})

}

我假设这段代码的目的是每次路由参数更改时重新获取数据?如果这是正确的,则 getProduct 调用需要在订阅方法中。

喜欢这个:

ngOnInit() {
this.route.params.subscribe(
(params: any) => {
this.productIndex = params['id'];
this.PService.getProduct(this.productIndex).subscribe((data: any) =>{
// return the object
console.log(data.product)
return this.selectedProduct = data.product,
//output the here object
console.log(this.selectedProduct);
});
});
// output undefined 
console.log(this.selectedProduct);
}

最后一个控制台.log将显示一个 undefined,因为它是在初始化组件时和检索产品之前执行的。

以下是正在发生的事情:

  1. 该组件已初始化并运行 ngOnInit。
  2. 参数已订阅。
  3. 底部的控制台日志尝试显示选定的 产品,没有...所以没有定义。
  4. 处理参数的更改,并将代码params.subscribe()被执行。
  5. 参数从路由中获取并用于调用 获取产品。
  6. 订阅了从 getProduct 返回的可观察量。
  7. 在稍后的某个时间点,数据从后端返回 服务器和getProduct().subscribe()中的代码是 执行。
  8. getProduct().subscribe()中的两个控制台日志是 执行并显示相应的产品。

有意义?

最新更新