如何在 Angular 中刷新组件

How to Refresh a Component in Angular

我正在做一个 Angular 项目。我正在努力处理组件中的刷新操作。

我想在单击按钮时刷新路由器的组件。 当我点击它时我有刷新按钮 component/router 需要刷新。

window.location.reload()location.reload()我都试过了,这两个都不适合我的需要。请知道的朋友帮忙

这可以通过 hack 来实现,导航到一些示例组件,然后导航到您要重新加载的组件。

this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);

在 angular 2 中刷新(硬方式)页面的其他方式 看起来像 f5

import { Location } from '@angular/common';

constructor(private location: Location) {}

pageRefresh() {
   location.reload();
}

经过一些研究和如下修改我的代码后,该脚本对我有用。我刚刚添加了条件:

this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
    this.router.navigate(['Your actualComponent']);
}); 

将此添加到所需组件的构造函数的代码对我有用。

this.router.routeReuseStrategy.shouldReuseRoute = function () {
  return false;
};

this.mySubscription = this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    // Trick the Router into believing it's last link wasn't previously loaded
    this.router.navigated = false;
  }
});

确保从 ngOnDestroy() 中的此 mySubscription unsubscribe

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

有关详细信息,请参阅此线程 - https://github.com/angular/angular/issues/13831

使用 this.ngOnInit(); 重新加载相同的组件而不是重新加载整个页面!

DeleteEmployee(id:number)
  {
    this.employeeService.deleteEmployee(id)
    .subscribe( 
      (data) =>{
        console.log(data);

        this.ngOnInit();

      }),
      err => {
        console.log("Error");
      }   
  }

在我的应用程序中,我有组件,所有数据都来自 API,我在组件的构造函数中调用它。 有一个按钮可以用来更新我的页面数据。单击按钮我在后端保存数据并刷新数据。 所以 reload/refresh 组件 - 根据我的要求 - 只是刷新数据。 如果这也是您的要求,则使用在组件构造函数中编写的相同代码。

幸运的是,如果您使用的是 Angular 5.1+,则不再需要实施 hack,因为已添加本机支持。您只需要在 RouterModule 选项中 将 onSameUrlNavigation 设置为 'reload' :

@ngModule({
 imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
 exports: [RouterModule],
 })

可在此处找到更多信息:https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

// reload page hack methode

push(uri: string) {
    this.location.replaceState(uri) // force replace and no show change
    await this.router.navigate([uri, { "refresh": (new Date).getTime() }]);
    this.location.replaceState(uri) // replace
  }
constructor(private router:Router, private route:ActivatedRoute ) { 
}

onReload(){
 this.router.navigate(['/servers'],{relativeTo:this.route})
}

没有明确路线的另一种方式:

async reload(url: string): Promise<boolean> {
  await this.router.navigateByUrl('.', { skipLocationChange: true });
  return this.router.navigateByUrl(url);
}

只需这样做:(对于 angular 9)

import { Inject } from '@angular/core';    
import { DOCUMENT } from '@angular/common';

constructor(@Inject(DOCUMENT) private document: Document){ }

someMethode(){ this.document.location.reload(); }

这有点开箱即用,我不知道这是否对你有帮助,但你试过了吗

this.ngOnInit();

它是一个函数,因此无论您有什么代码,都会像刷新一样被调用。

html 文件

<a (click)= "getcoursedetails(obj.Id)" routerLinkActive="active" class="btn btn-danger">Read more...</a>

ts 文件

  getcoursedetails(id)
  { 
  this._route.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
    this._route.navigate(["course",id]);
  }); 

只需从 angular 路由器更改 routeReuseStrategy

this._router.routeReuseStrategy.shouldReuseRoute = function () {
      return false;
    };

将路由器属性“导航”设置为 false:

this._router.navigated = false;

然后导航到您的组件:

this._router.navigate(['routeToYourComponent'])

之后恢复 old/default routeReuseStrategy:

this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
          return future.routeConfig === curr.routeConfig;

你也可以用这个做一个服务:

@Injectable({
  providedIn: 'root'
})
export class RouterService {

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _router: Router
  ) { }

  reuseRoutes(reuse: boolean) {
    if (!reuse) {
      this._router.routeReuseStrategy.shouldReuseRoute = function () {
        return false;
      };
    }
    if (reuse) {
      this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig;
      };
    }
  }

  async refreshPage(url?: string) {
    this._router.routeReuseStrategy.shouldReuseRoute = function () {
      return false;
    };

    this._router.navigated = false;

    url ? await this._router.navigate([url]) : await this._router.navigate([], { relativeTo: this._activatedRoute });

    this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
      return future.routeConfig === curr.routeConfig;
    };
  }
}

router.navigate['/path']只会带你到指定路径
使用 router.navigateByUrl('/path')
它重新加载整个页面

reload () { this.ngOnInit(); }

之前的部分回答有问题:

  1. 不应直接调用 ngOnInit() 等生命周期方法。
  2. 重新导航到某些 URL 是一个次优的解决方案,尤其是当您动态加载的组件只是大页面的一小部分时

这对我有用(我不知道它是否值得推荐或最佳)

  1. 在要动态加载的组件中,添加对ChangeDetectorRef.
  2. public引用
  3. 我假设动态加载的数据有一些输入数据(示例中的“tags”),这些数据会在事后更新并产生渲染问题。
  @Input()
  tags: string[] = [];

  constructor(public changeDetector: ChangeDetectorRef )
  1. 在动态加载的父组件中,动态创建子组件并可能为其设置一些数据后,调用创建实例的changeDetector.markForCheck()如下:
  constructor(private vcrf: ViewContainerRef, private cfr: ComponentFactoryResolver, private elementRef: ElementRef) {
  }

  public loadComponent(): void {

    const componentFactory = this.cfr.resolveComponentFactory(TagsListComponent);
    const component = this.container.createComponent(componentFactory);
    component.instance.tags = /* whatever data we want to pass */;
    component.instance.changeDetector.markForCheck();
    ...

loadComponent()是一个自定义函数,可以调用,比如一旦父页面滚动到父组件的某个位置,说明动态组件应该是显示。

只需按照以下步骤操作即可:

  1. 在您的应用程序中添加 {onSameUrlNavigation: 'reload'},如下所示-routing.modules.ts

@NgModule({
imports: [ RouterModule.forRoot(routes,{onSameUrlNavigation: 'reload'})],
exports: [ RouterModule ]
})

  1. 在您的组件 ts 文件构造函数中添加 this.router.routeReuseStrategy.shouldReuseRoute = () => false,如下所示:
constructor(private router: Router) {
      this.router.routeReuseStrategy.shouldReuseRoute = () => false;
  }
  1. 现在单击按钮并调用 ajax 服务器调用,从服务器获取所需数据并用新数据替换 TS 文件中的全局变量。
  2. 在最后调用this.router.navigate([/sameRoute]);。 将 sameRoute 替换为您的路线 url.

  3. 确保在刷新按钮的 onClick 方法末尾 return false,否则会导致主路由页面而不是同一页面重新加载。

    这些步骤将重新加载您的页面。 :)

更多详情:https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

我正在使用 Angular 12.

在我的例子中,我需要重新加载特定的路由(不是应用程序中的所有路由),所以添加全局设置 {onSameUrlNavigation: 'reload'} 没有效果,而组件中的 this.router.routeReuseStrategy.shouldReuseRoute = () => false 有效但修改了全局设置路由器设置。

解决方案是将原始路由器配置保存到一个变量,然后在组件的构造函数中更改它,如问题的第一个答案所示@abhishek-singh。

private routeReuseStrategy:any;

  constructor(
    private router:Router
  ) {
    this.routeReuseStrategy = this.router.routeReuseStrategy.shouldReuseRoute;
    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
  }

并且在退出路径时,使用 OnDestroy 挂钩重新映射原始配置。

   public ngOnDestroy():void
   {
     this.router.routeReuseStrategy.shouldReuseRoute = this.routeReuseStrategy;
   }

调用 ngOnInit() 对我的复杂组件不起作用,我最终使用了这个

reloadCurrentRoute() {
    let currentUrl = this.router.url;
    this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
        this.router.navigate([currentUrl]);
    });
}