Angular 主动路由解析程序在每次调用时返回未定义
我一直在为激活的路由准备一个解析器。我遇到的问题是,在路由组件中,我试图从解析器获取的数据总是未定义的。我知道我的服务是有效的(我已经向控制台返回了值),只是当我尝试订阅组件中的路由数据时,没有返回任何内容 这是我的组件Angular 主动路由解析程序在每次调用时返回未定义,angular,typescript,angular-router,angular-resolver,Angular,Typescript,Angular Router,Angular Resolver,我一直在为激活的路由准备一个解析器。我遇到的问题是,在路由组件中,我试图从解析器获取的数据总是未定义的。我知道我的服务是有效的(我已经向控制台返回了值),只是当我尝试订阅组件中的路由数据时,没有返回任何内容 这是我的组件 @Component({ selector: 'app-value', templateUrl: './value.component.html', styleUrls: ['./value.component.css'] }) export class ValueCo
@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();
}
@可注入({
providedIn:'根'
})
导出类LinkResolver实现解析{
构造函数(专用路由器:路由器,专用数据库服务:数据库服务){}
解析(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot):可观察{
console.log('在路由器中');
返回这个.dbservice.getBins();
}
最后是服务
getBins(): Observable<Bins[]> {
return this.http.get<Bins[]>('http://localhost:5000/api/values');
}
getBins():可观察{
返回此.http.get('http://localhost:5000/api/values');
}
问题出在app.component html模板中。显然,您需要添加html标记
,以便将数据路由到您的视图。您可以订阅并检查您是否从解析程序本身获取getBins吗?我直接在我的组件中运行解析程序,并且我可以订阅并从m返回值y APIngOnInit(){this.dbService.getBins().subscribe(response=>{this.values=response;});this.linkresolver.resolve().subscribe(res=>{this.bins=res;console.log(this.bins);}