活动路由解析器在每次呼叫时返回未定义

时间:2018-09-07 19:06:57

标签: angular typescript angular-router angular-resolver

我一直在努力让分解器针对激活的路线进行研究。我遇到的问题是,在路线的组件中,我尝试从解析器获取的数据始终未定义。我知道我的服务有效(我已将值返回到控制台),只是当我尝试订阅组件中的路由数据时,什么也没返回

这是我的组成部分

 @Component({
 selector: 'app-value',
 templateUrl: './value.component.html',
 styleUrls: ['./value.component.css']
})
export class ValueComponent implements OnInit , OnDestroy {

values: any = {};
newBin: any = [];
navigationSubscription;
bins: Bins;

constructor(private http: Http, private dbService: DbService,           private toastr: ToastrService, private router: Router,
private route: ActivatedRoute) {
this.navigationSubscription = this.router.events.subscribe((e: any) => {
 if (e instanceof NavigationEnd) {
    this.loadLinks();
  }
});
}

ngOnInit() {
 this.dbService.getBins().subscribe( response => {
  this.values = response;
 }
);
 this.loadLinks();
}

loadLinks() {
this.route.data.subscribe(data => {
  this.bins = data['bins'];
  console.log(this.bins);
 });
}

这是我的app.module路线

@NgModule({
  declarations: [
  AppComponent,
  ValueComponent,
  ],
  imports: [
  BrowserModule,
  HttpModule,
  RouterModule.forRoot(
  [{path: 'bins', component: ValueComponent, resolve: {bins: LinkResolver}, runGuardsAndResolvers: 'always'},
  {path: '', redirectTo: 'bins', pathMatch: 'full' }],
  {onSameUrlNavigation: 'reload'}),

这是解析器

 @Injectable({
 providedIn: 'root'
 })
 export class LinkResolver implements Resolve<any> {

constructor(private router: Router, private dbservice: DbService) {}

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
    console.log('in the router');
    return this.dbservice.getBins();
}

最后是服务

getBins(): Observable<Bins[]> {
return this.http.get<Bins[]>('http://localhost:5000/api/values');
}

1 个答案:

答案 0 :(得分:0)

问题出在app.component html模板中。显然,您需要添加html标签<router-outlet></router-outlet>以便将数据路由到您的视图。

相关问题