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

时间:2017-11-18 00:04:43

标签: angular

我有一个显示项目列表的组件,可以使用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 个答案:

答案 0 :(得分:1)

在路线中将属性runGuardsAndResolvers设置为&#39;始终&#39;这样:

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

每次访问路径时都会执行解析。

此致