【问题标题】:Active Route Resolver Returns Undefined On Every Call活动路由解析器在每次调用时返回未定义
【发布时间】:2019-02-13 03:37:03
【问题描述】:

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

这是我的组件

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

【问题讨论】:

  • 您可以订阅并检查您是否从解析器本身获取 getBins 吗??
  • 我直接在我的组件中运行了解析器,我能够从我的 API ngOnInit() { this.dbService.getBins().subscribe( response =&gt; { this.values = response; } ); this.linkresolver.resolve().subscribe(res =&gt; { this.bins = res; console.log(this.bins); }); } 订阅和返回值

标签: angular typescript angular-router angular-resolver


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2021-08-14
    相关资源
    最近更新 更多