Angular 如何使用route参数作为服务方法的参数?
我正在尝试将产品详细信息转到单个产品的路线。 现在 我有一个id参数的单一产品的路线,它的工作良好Angular 如何使用route参数作为服务方法的参数?,angular,typescript,rxjs,angular-routing,angular-services,Angular,Typescript,Rxjs,Angular Routing,Angular Services,我正在尝试将产品详细信息转到单个产品的路线。 现在 我有一个id参数的单一产品的路线,它的工作良好 { path: 'single-product/:id', component: SingleProductComponent } 在组件类型脚本中: id: string; private mainSub: any; public ngOnInit(): void { this.mainSub = this.route.params.subscribe(params => {
{ path: 'single-product/:id', component: SingleProductComponent }
在组件类型脚本中:
id: string;
private mainSub: any;
public ngOnInit(): void {
this.mainSub = this.route.params.subscribe(params => {
this.id = params['id'];
}
this.productsService
.all()
.map(res => res.filter(item => item.id === this.id))
.subscribe(resp => console.log(resp));
});
}
在控制台中,我得到了正确的产品,但如何才能将数据获取到视图中?使用以下代码在组件中实现:
id: string;
product: any;
private mainSub: any;
public ngOnInit(): void {
this.mainSub = this.route.params.subscribe(params => {
// I used + sign if id is number otherwise remove it
this.id = +params['id'];
this.productsService
.all()
.map(res => res.find(item => item.id === this.id))
.subscribe(resp => this.product = resp);
});
}
}
import 'rxjs/add/operator/switchMap'; // Maybe replace with lettable operators
@Component({...})
export class FooComponent {
product$: Observable<Product>;
constructor(private _route: ActivatedRoute, private _productService: ProductService){
this.product$ = _route.paramMap
.map(params => params.get('id')) // maps the route params. map to the id key
.switchMap(id => _productService.getById(id));// change the main stream to the stream returned by the service
}
}
现在在html模板中使用以下数据(虚拟html):
品名
{{product.productName}
第一件事:
让我们在服务类中封装该筛选器逻辑:
export interface Product {
// define the properties for your product
}
@Inject()
export class ProductService {
....
// constructor injetction and other methods
....
all(): Observable<Product[]>{
// implementation
}
getById(id:string): Observable<Product> {
// or maybe could your backend offer an endpoint that does this for you?
// something like `root/api/products/:id`;
return this.all().map(products => products.find(product => product.id === id));
}
}
我已经这样做了,但是出现了错误“无法读取未定义的属性'name'”您可以将您的响应粘贴到此处吗。console.log响应实际上是有效的,但是为什么在获取数据时在控制台中出错?您可以在此处注释登录到浏览器控制台的错误。代码很好,可能在使用中出现了一些问题。
import 'rxjs/add/operator/switchMap'; // Maybe replace with lettable operators
@Component({...})
export class FooComponent {
product$: Observable<Product>;
constructor(private _route: ActivatedRoute, private _productService: ProductService){
this.product$ = _route.paramMap
.map(params => params.get('id')) // maps the route params. map to the id key
.switchMap(id => _productService.getById(id));// change the main stream to the stream returned by the service
}
}
<ng-container *ngIf="product$ | async as product">
{{ product | json }}
// your template goes here
</ng-container>