当我从产品重定向到产品/详细信息时,URL显示错误的ID

时间:2018-10-06 16:06:14

标签: angular firebase angular5 google-cloud-firestore

我正在尝试从产品列表重定向到product-details页,但是我的URL显示的ID值错误:

例如:https://cafe-c3c52.firebaseapp.com/admin/products;node_=%5Bobject%20Object%5D;ref_=https:%2F%2Fcafe-c3c52.firebaseio.com%2Fproducts%2F-LNpWrMiZ8YRAiaf8K9q;index_=.priority

正确的是: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);
  }
}

1 个答案:

答案 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);
        }
      });
  }

}