产品.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 和 data 但是当 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']);
}
}