本文介绍了无法在 Angular 2 中使用 Resolve的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 angular4 中呈现视图之前加载对象,所以我选择使用 angular4 的解析但我无法获取数据,不知道我做错了什么.
I want to load object before the view is rendered in angular4, so i choose to use resolve of angular4 but i am not able to get data, dont know what am i doing wrong.
这是我的模块
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ActivatedRoute, Routes, RouterModule } from '@angular/router';
import { ResolverService } from './resolver.service';
export const routes: Routes = [
{ path: '', component: AppComponent, resolve: { transaction: ResolverService } }
];
@NgModule({
declarations: [
AppComponent
],
imports: [
RouterModule.forRoot(routes),
BrowserModule,
FormsModule
],
providers: [ResolverService],
bootstrap: [AppComponent]
})
export class AppModule { }
我的解析器服务
import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ResolverService implements Resolve<any> {
constructor(private router: Router) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
return new Observable(observer => {
setTimeout(function () {
observer.next(150)
}, 1000);
});
}
}
这是我的组件
import { Component, AfterViewInit, APP_INITIALIZER, InjectionToken, Inject } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot, ActivatedRoute } from '@angular/router';
import { student } from './sa-model.service';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
constructor(private route: ActivatedRoute) {
}
ngAfterViewInit() {
this.route.data.subscribe(success => {
debugger;
console.log(success);
})
}
}
但在组件中,我期望得到我在解析器服务中传递的值 150,但我没有得到任何值
but in the component i was expecting to get the value 150 which i am passing in the resolver service, but i am not getting any values
任何人都可以指导我到底做错了什么
can any one guide me on what exactly am in doing wrong
推荐答案
这是因为您打开了 observable 但在返回它之前从未完成它,所以没有返回任何内容.添加这个:
It's because you opened the observable but never completed it before returning it, so nothing gets returned. Add this:
setTimeout(function () {
observer.next(150);
observer.complete(); // Need to call complete once done.
}, 1000);
这篇关于无法在 Angular 2 中使用 Resolve的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!