product.service.ts:オブジェクトが未定義に変更されましたか?
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と同じように成功します。単一の製品にパラメータの変更をするたびに取得するようにしてくださいます
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);
});
});
}
その方法:
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 = data - >これを呼び出すと、 'this.product'は定義されていません。 – diopside
ProductDetailComponentでは、APIから製品の詳細を取得しようとしているときに 'this.id'が定義されていないようです。 しかし、このAPIコールはルートパラメータのIDに依存しているように見えるので、APIコールでIDを取得するobservableをネストするか、 'switchMap'を使用する必要があります。 – Catalyst
私はすでにそれをチェックしました。そしてthis.idは価値があります。私は自分のコードを分かりやすくしたい、私は角度2で新しいので、それに精通していない。私に例を与えることができますか?ありがとう。 –