首页 文章

当url queryParams更改时,Angular 4路由器重新加载视图

提问于
浏览
0

我有一个显示项目列表的组件,可以使用url queryParams进行过滤,这些项目是从api中分页的,如果设置了过滤器,我需要再次调用第一页,第一次调用是在解析器中路由器,所以我需要的是路由器的重新加载方式与我来自其他URL的方式相同 .

app.routes.ts

const appRoutes: Routes = [
    {
        path: 'applications',
        component: AppComponent,
        resolve: {
            data: AppResolve
        }
    },
]

app.resolver.ts

@Injectable()
export class AppResolve implements Resolve<any> {
    constructor() {}
   resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
           // call to the api and the first 50 applications filtered by the url queryParams
    }
}

app.component.ts

@Component({
    // ...
})
export class AppComponent {
    constructor(private route: ActivatedRoute,
              private appService: AppService) {
        this.route.data.subscribe((data: any) => {
            // recive the first 50 applications
        })
    }

    loadMoreApps(): void {
        // call to the api for the next 50 applications filtered by the url queryParams
    }
}

app.service.ts

@Injectable()
export class AppService {
    constructor(private router: Router,
              private route: ActivatedRoute) {}
    navigate(urlQueryParams: any): void {
        this.router.navigate(['/applications'], {queryParams: urlQueryParams});
    }
}

other.component.ts

@Component({
    // ...
})
export class OtherComponent {
    constructor(private appService: AppService) {}
    filterApps(): void {
        const filters = {
            'category': 'game',
            'author': 'username'
        }
        this.appService.navigate(filters)
    }
}

1 回答

  • 1

    在路由中将属性runGuardsAndResolvers设置为“always”,方式如下:

    const appRoutes: Routes = [
    {
        path: 'applications',
        component: AppComponent,
        resolve: {
            data: AppResolve
        },
        runGuardsAndResolvers: 'always' // <----- This line
    }
    

    ]

    这将在您每次访问路径时执行解析 .

    问候

相关问题