angular - 活动路由解析器在每次调用时返回未定义
问题描述
我一直在努力让解析器为激活的路线工作。我遇到的问题是,在我的路由组件中,我试图从解析器获取的数据始终是未定义的。我知道我的服务有效(我已将值返回到控制台),就在我尝试订阅组件中的路由数据时,没有返回任何内容
这是我的组件
@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');
}
解决方案
问题出在 app.component html 模板中。显然,您需要添加 html 标记<router-outlet></router-outlet>
才能将数据路由到您的视图。
推荐阅读
- android - 使用列值从房间检索数据 - 房间
- ios - UITableViewCell 的 ViewModel:“允许”数据库操作?
- javascript - 如何生成带有变量的链接?使用 javascript、jquery
- java - Camel 将参数转移到错误的级别
- javascript - React/Ant Design 修复后退按钮
- java - 如何在 2 活动中使用相同的 ImageView
- javascript - 如何将范围的值传递给我的变量调用?
- python - subprocess.Popen() 返回值中的 stderr 来自哪里?
- osgi - 使用 Equinox 启动器在 OSGi 中使用多个配置文件
- powershell - 如何使用 powershell 获取线程等待原因?