以外我在控制台登录选定的属性时在ngOnInit
它提供了控制对象,但在此块之外,当我控制此属性它是未定义的。可有些怎样的帮助得到它的工作..或任何其他解决方案属性未定义在组件中通过订阅get方法在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);
})
}
可能的重复[如何返回从angular2中的Observable/http/async调用的响应?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response- from-an-observable-http-async-call-in-angular2) – Alex
你甚至检查过重复的问题吗?它在回调之外始终是未定义的。 – Alex
谢谢。很多.. :) –