如何重载当前的Angular 2组件

How to reload the current Angular 2 Component

本文关键字:Angular 2组件 何重载 重载      更新时间:2023-09-26

如何在Angular 2中重新加载相同的组件?

下面是我的代码:
import { Component, OnInit, ElementRef, Renderer } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { productModel } from '../_models/index';
import { categoryListService } from '../_services/index';
@Component({
  selector: 'app-product',
  templateUrl: 'product.component.html',
  styleUrls: ['product.component.css']
})
export class productComponent implements OnInit {
  uidproduct: productModel;
  param: number;
  constructor(
    private elementRef: ElementRef,
    private route: ActivatedRoute,
    private router: Router,
    private categoryListService: categoryListService) { }
  ngOnInit() {
    this.route.params.subscribe(product => {
      console.log('logging sub product obj', product);
    });
    this.uidproduct = JSON.parse(sessionStorage.getItem('product'));
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://this/external/script/needs/to/be/loaded/each/time.js";
    this.elementRef.nativeElement.appendChild(s);
  }
  nextproduct(){ 
    let i = this.uidproduct.order;
    this.categoryListService.findNextproduct(this.uidproduct);
    this.param = ++i;
    this.router.navigate([`/product/${this.param}`]);
  }
}

nextproduct()与模板中的单击事件绑定。

uidproduct是一个JSON对象,有许多属性,我正在更新的DOM与{{uidproduct.classname}}

我在模板中像这样使用它:

<div id="selected-product" class="{{uidproduct.classname}}">

当我点击<button (click)="nextproduct()">时,它将改变DOM中的类属性,但我需要重新加载组件以使外部脚本生效。

您可以使用*ngIf来重新呈现模板的内容:

@Component({
  selector: '...',
  template: `
<ng-container *ngIf="!rerender">
 template content here
</ng-container>`
})
export class MyComponent {
  rerender = false;
  constructor(private cdRef:ChangeDetectorRef){}
  doRerender() {
    this.rerender = true;
    this.cdRef.detectChanges();
    this.rerender = false;
  }
}

我不明白为什么你需要重新加载组件。如果绑定到uidproduct的各个字段,那么重新加载应该会刷新组件中显示的值。所以,重新加载组件只会增加开销。

如果你认为你仍然需要这样做的原因在这里没有提到,那么你应该这样做:

  1. 导航到另一个(可能是空白的)组件。
  2. 直接返回。

问题是你需要等待第一个导航完成后再进行第二个导航。

在组件中导入NavigationEnd:

import { Router, NavigationEnd } from '@angular/router';

然后在构造函数中订阅它:

constructor(private thingService: ThisThingService, private router: Router) { 
   router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
      if (event.url === '/blank') {
        this.router.navigate(['product']); 
      }
    }
  });

请注意,我等待NavigationEnd发生,然后检查是否路由到空白组件。如果是空白组件的路径,则导航回产品。如果你真的需要传递那个ID,只需将它存储在你的对象中并添加到这里。

与其在nextproduct()中路由到你的产品页面,不如导航到blank

this.router.navigate(['blank']);

这样就可以很好地重新加载组件了。

为了简单起见,我故意留下的问题是构造函数中的subscribe调用将在每次重新加载时执行。因此,作为对读者的一个练习,把它从构造函数中取出来,为它创建一个漂亮的服务,或者把它移到你的应用组件的构造函数中,或者移到你的路由模块中,或者任何你认为有意义的地方。