我正在尝试从产品列表重定向到product-details
页,但是我的URL显示的ID值错误:
正确的是:https://cafe-c3c52.firebaseapp.com/admin/products/id
您能帮我找出问题所在吗?
admin-products.component.html
<tbody>
<tr *ngFor="let p of products$ | async">
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td><a [routerLink]="['/admin/products/', p.key]"> Edit</a> </td>
<td> {{p.key}}</td>
</tr>
</tbody>
admin-products-component.ts
export class AdminProductsComponent implements OnInit {
products$;
constructor(private productService: ProductService) {
this.products$ = this.productService.getAll();
}
...
}
products.form.component
export class ProductsFormComponent implements OnInit {
categories$;
product;
constructor(
private router: Router,
private route: ActivatedRoute,
private categoryService: CategoryService,
private productService: ProductService
) {
this.categories$ = categoryService.getCategories();
const id = this.route.snapshot.paramMap.get('id');
if (id) {
this.productService.get(id).snapshotChanges().pipe(
take(1)).subscribe(p => this.product = p);
}
}
}
产品服务
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private db: AngularFireDatabase) {}
getAll() {
return this.db.list('/products').snapshotChanges().map(
changes => {
return changes.map(c => ({
key: c.payload,
...c.payload.val()
}));
});
}
get(productId) {
return this.db.object('/products/' + productId);
}
}
答案 0 :(得分:0)
那是因为您正在使用this.route.snapshot.paramMap.get('id');
。理想情况下,您应该订阅this.route.params
(即BehaviorSubject
)以获取更新的ID。
此外,您应该尝试使constructor
的重量尽可能轻。因此,请考虑将您的constructor
代码移至ngOnInit
像这样更改您的ProductsFormComponent
实现
export class ProductsFormComponent implements OnInit {
categories$;
product;
constructor(
private router: Router,
private route: ActivatedRoute,
private categoryService: CategoryService,
private productService: ProductService
) { }
ngOnInit() {
this.categories$ = categoryService.getCategories();
this.route.params
.subscribe(params => {
const id = params['id'];
if (id) {
this.productService.get(id).snapshotChanges().pipe(
take(1)).subscribe(p => this.product = p);
}
});
}
}