angular 9 订阅空

angular 9 subscribe null

产品服务:

   product:IProduct;
  products:IProduct[] = [];
  id:number;
  constructor(private productSevice:ProductService, private route: ActivatedRoute) { 

  }

  ngOnInit(): void {
    this.id= parseInt(this.route.snapshot.paramMap.get('id'));
     console.log(this.productSevice.products)

    this.productSevice.getById(this.id).subscribe(data => {
      this.product = data;
      console.log(data)

    })
console.log(this.product)
  }

产品:

  product:IProduct = null;

  id:any;

 

不管我在尝试什么,产品都是空的!

when i'm doing console.log in the subscribe i can see the data! but the product still null. | -> I tried that also onInit same result -<

  constructor(private productSevice:ProductService, private route: ActivatedRoute) { 

    this.id = this.route.snapshot.paramMap.get('id'); // line 'x'

    this.productSevice.getById(this.id).subscribe(data => {

      this.product = data; // line 'y'
    });

    console.log(this.product)   // line 'z'
 }

行 'x' 和 'z' 首先执行,稍后当您收到请求的响应时,将执行传递给订阅的函数。因此,如果您尝试在此函数之外记录产品,您将看不到 data,因为 this.product 尚未分配给它。

因此您可以检查 this.product 是否在订阅块中正确分配。

  constructor(private productSevice:ProductService, private route: ActivatedRoute) { 
    this.id = this.route.snapshot.paramMap.get('id');
    this.productSevice.getById(this.id).subscribe(data => {
      this.product = data;
      console.log(this.product)
    });
 }

并且在构造函数中发送 HTTP 请求不是一个好习惯。在 ngOnInit 生命周期挂钩中执行此操作。