[英]How to reload the current Angular 2 Component
如何在 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 对象,它具有许多属性,我正在使用{{uidproduct.classname}}
更新 DOM
我在这样的模板中使用它:
<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
的各个字段,则重新加载应该会刷新组件中显示的值。 因此,重新加载组件只会增加开销。
如果您认为您仍然需要这样做,这里没有提到一个很好的原因,那么您可以这样做:
问题是您需要等待第一个导航完成才能进行第二个导航。
在您的组件中,导入 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()
中路由到您的产品页面, nextproduct()
导航到blank
。
this.router.navigate(['blank']);
这应该可以完美地重新加载您的组件。
为了简单起见,我故意留下的问题是构造函数中的subscribe
调用将在每次重新加载时执行。 因此,作为读者的练习,将它从构造函数中取出并为其创建一个很好的服务,或者将它移到您的应用程序组件的构造函数中,或者移至您的路由模块或任何对您有意义的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.