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']);
}
}
嗨 - 你是說當你調用這個 - > this.product = data - >它告訴你'this.product'是不確定的嗎? – diopside
在ProductDetailComponent中,當您嘗試從API獲取產品詳細信息時,它看起來像'this.id'沒有定義。 但是它看起來像這個API調用依賴於路由參數的ID,因此您應該嵌套將API帶給您的可調參數與API調用或使用'switchMap'。 – Catalyst
我已經檢查過它。而this.id有價值。我希望我的代碼容易理解,我也是新的角2,所以我不熟悉這一點。可以舉個例子嗎?謝謝。 –