如何使零件成角度以在路线更改时重新渲染?

时间:2019-06-07 08:14:51

标签: angular7

我有一个Angular 7页面组件,其中包含另一个组件。从小组件的选择框中选择产品时,它将导航到具有相同页面组件(ProductDetails),但url中具有不同参数(不同productId)的另一页。

选择产品时在小组件上导航:

onProductSelected(args) {
    const selectedOption = args.target.value;
    this.router.navigate(['/products', selectedOption]);
  }

页面组件ProductDetails.ts:

@Component({
    selector: 'product-details',
    templateUrl: './product-details.component.html',
    styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit, OnDestroy {
    currentProductId: string;
    product: ProductModel;
    subscriber;

    constructor(private productService: ProductService,
                private route: ActivatedRoute) {}

    ngOnInit() {
        this.currentProductId = _.get(this.route, 'snapshot.params.productId');
        this.subscriber = this.productService.getProdactById(this.currentProductId)
            .subscribe(res => {
                this.product = res;
            });
    }

    ngOnDestroy() {
        if (this.subscriber) {
            this.subscriber.unsubscribe();
        }
    }
}

我需要页面组件的ngOnInit来注意url更改并重新创建自己。 (以获取新的productId参数并呈现产品详细信息)。 我该怎么办?

谢谢!

1 个答案:

答案 0 :(得分:0)

角度router params是可观察的。可以用来订阅参数值的更改,这些更改随后可以使用map或其他RxJs运算符传递给服务进行操作。

@Component({
    selector: 'product-details',
    templateUrl: './product-details.component.html',
    styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {
    product$: Observable<ProductModel>;

    constructor(private productService: ProductService,
                private route: ActivatedRoute) {}

    ngOnInit() {
        this.product$ = route.params.pipe(
            map(params => params.productId),
            map(productId => this.productService.getProdactById(productId))
        );
    }
}

现在,您可以使用async管道在模板中使用产品可观察的值,而无需处理订阅:

<div *ngIf="product$ | async as product">
  <p>Product name {{product.name}}</p>
</div>

请参阅此stackblitz

中的示例