0

我一直在努力让解析器为激活的路线工作。我遇到的问题是,在我的路由组件中,我试图从解析器获取的数据始终是未定义的。我知道我的服务有效(我已将值返回到控制台),就在我尝试订阅组件中的路由数据时,没有返回任何内容

这是我的组件

 @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');
}
4

1 回答 1

0

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

于 2018-09-11T21:12:17.447 回答