对象更改为undefined?
问题描述:
product.service.ts:对象更改为undefined?
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map'
@Injectable()
export class ProductService {
private apiUrl = "http://59a4442f42dc220011f771ad.mockapi.io/api/products/";
constructor(private http: Http) { }
GetList(): Observable<any[]> {
return this.http.get(this.apiUrl).map((res: Response) => res.json());
}
GetSingle(id: number): Observable<any> {
return this.http.get(this.apiUrl+id).map((res: Response) => res.json());
}
}
我有这样的服务。
而且我在这里有一个产品列表:product.component.ts
import { Component, OnInit } from '@angular/core';
import { ProductService } from "../Shared/Services/products.service";
@Component({
selector: "app-product",
templateUrl: "App/Product/product.component.html",
})
export class ProductComponent implements OnInit {
ngOnInit(): void {
this.productsService.GetList().subscribe((response: any) => {
this.products = response;
});
}
public products: any[];
constructor(private productsService: ProductService){}
}
我的问题是存在的。我可以得到id和数据,但是当this.product = data时。该产品是未定义的。我已经检查了数据,我想知道为什么我失败了。我在product.component上做了同样的事情并取得了成功。
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { Subscription } from 'rxjs';
import { ProductService } from "../Shared/Services/products.service";
@Component({
selector: "app-product-detail",
templateUrl: "App/Product/product-detail.component.html",
})
export class ProductDetailComponent implements OnInit, OnDestroy {
public id: number;
public subscription: Subscription;
public product;
constructor(private router: Router, private activatedRoute: ActivatedRoute, public productService: ProductService){}
ngOnInit(): void {
this.subscription = this.activatedRoute.params.subscribe(params => {
this.id = params['id'];
});
this.productService.GetSingle(this.id).subscribe((data) => {
this.product = data;
});
alert(this.product);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
goToProductPage() {
this.router.navigate(['product']);
}
}
答
在ngOnInit的代码需要内部认购的参数,如:
ngOnInit(): void {
this.subscription = this.activatedRoute.params.subscribe(params => {
this.id = params['id'];
this.productService.GetSingle(this.id).subscribe((data) => {
this.product = data;
alert(data);
alert(this.product);
});
});
}
这样,这将是确保每一次的参数变化,以获得单品。
嗨 - 你是说当你调用这个 - > this.product = data - >它告诉你'this.product'是不确定的吗? – diopside
在ProductDetailComponent中,当您尝试从API获取产品详细信息时,它看起来像'this.id'没有定义。 但是它看起来像这个API调用依赖于路由参数的ID,因此您应该嵌套将API带给您的可调参数与API调用或使用'switchMap'。 – Catalyst
我已经检查过它。而this.id有价值。我希望我的代码容易理解,我也是新的角2,所以我不熟悉这一点。可以举个例子吗?谢谢。 –