我已更改了我的组件模板html,但更改未反映在我的应用中。有没有办法强制应用程序刷新所有组件和模板?
环顾四周,大多数人都说要使用
ApplicationRef.tick()
- 类似于Angular 1' $rootScope.$digest()
- 即检查完整的组件树
NgZone.run(callback)
- 类似于$rootScope.$apply(callback)
- 即评估Angular 2区域内的回调函数。我想,但我不确定,这会在执行回调函数后检查完整的组件树。
ChangeDetectorRef.detectChanges()
- 与$scope.$digest()
类似 - 也就是说,只检查此组件及其子组件
但如果您更改变量并需要刷新组件,它们似乎都适用。我所做的就是更改一些html并想重新渲染已更改的html,但它似乎是缓存的。
我按照以下方式尝试ChangeDetectorRef
,但它似乎没有做任何事情:
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Router } from '@angular/router';
import { Hero } from '../classes/hero';
import { HeroService } from '../services/hero.service';
@Component({
selector: 'my-dashboard',
templateUrl: '/app/templates/dashboard.component.template.html', // I just want to refresh some changes I made in this file
changeDetection: ChangeDetectionStrategy.OnPush // I have tried with and without this - doesn't seem to do anything for me
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(
private ref: ChangeDetectorRef,
private router: Router,
private heroService: HeroService
) {
this.ref.markForCheck(); // make it check for changes
}
public ngOnInit(): void {
this.getHeroes();
}
public gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
private getHeroes(): void {
console.log('sdklfn;')
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1, 5));
}
}
或者是否有一个文件夹我可以删除以强制刷新?
答案 0 :(得分:1)
好吧,我似乎已经通过添加运行时编译器来手动清除缓存来解决我的问题 - 似乎需要以编程方式执行此操作(而不是只能删除一些文件)。但是,如果有人找到更好的解决方案,我会保持开放状态
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { RuntimeCompiler} from '@angular/compiler'; // add this
import { Hero } from '../classes/hero';
import { HeroService } from '../services/hero.service';
@Component({
selector: 'my-dashboard',
templateUrl: '/app/templates/dashboard.component.template.html', // I just want to refresh some changes I made in this file
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(
private runtimeCompiler: RuntimeCompiler, // add this
private router: Router,
private heroService: HeroService
) {
this.runtimeCompiler.clearCache(); // add this
}
public ngOnInit(): void {
this.getHeroes();
}
public gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
public getHeroes(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1, 5));
}
}
我也遇到过这个问题,其中有关如何清除模板缓存的更多变化:How to clear template cache