如何在不重新加载整个页面的情况下重新加载 Angular 中的组件

时间:2020-12-19 16:29:47

标签: javascript angular

我想重新加载路线但不重新加载整个页面。这不是我想要的:

window.location.reload();

我只想重新加载组件而不是页面。这是我试过的:

  1. Angular: Change the route without reloading
  2. Angular: Refetch data on same URL navigation

我还尝试了其他一些随机技巧。尝试了此 URL 中的以下代码:

  1. Angular Basics: Refresh an Angular Component without reloading the same Component

    mySubscription: any;
    
    constructor() {
      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;
        }
      })
    }
    

但是由于其他原因它不起作用。我需要一个解决方案。请提出其他建议。

1 个答案:

答案 0 :(得分:0)

skipLocationChange 选项对我有用,试试我的服务

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class ReloadRouteService {

  constructor(
    private router: Router,
  ) { }

  redirectTo(url: string): void {
    // When skipLocationChange true, navigates without pushing a new state into history.
    this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
        this.router.navigate([url]);
    });
  }
}
相关问题