2
我有一個Angular2解析器多次實例化的問題。angular2解析器多次實例化
這是我的功能模塊聲明(路由器延遲加載):
const ROUTES: Route[] = [
{
path: '',
component: ScreenParentComponent,
children: [
{
path: '',
component: InnerScreenParentComponent,
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'urlA'
},
{
path: 'urlA',
component: ChildComponentA,
resolve: [ResolverA, ResolverB]
}
]
}
]
}
];
@NgModule({
providers: [
ResolverA,
ResolverB
],
declarations: [
InnerScreenParentComponent,
ChildComponentA
],
imports: [
SharedModule,
RouterModule.forChild(ROUTES)
]
})
export class MyFeatureModule {
}
這是問題的解決程序代碼(姑且稱之爲ResolverA):
import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs";
import {AuthHttp} from "angular2-jwt";
@Injectable()
export class ResolverA implements Resolve<IDataDto> {
private API_URL = '...';
private _reasons: IDataDto[];
constructor(private http: AuthHttp) {
console.log("Resource NEW");
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
console.log("Resource RESOLVE");
return this.http.get(this.API_URL)
.map(result => result.json())
.do(result => this._reasons = result);
}
get reasons(): IDataDto[] {
return this._reasons;
}
}
export interface IDataDto {
reasonCode: string,
description: string,
gainLossType: GainLossType
}
export type GainLossType = "GAIN" | "LOSS";
而且一組件:
// All needed imports
@Component({
selector: 'componentA',
template: require('./componentA.template.html')
})
export class ComponentA implements OnInit {
constructor(private router: Router,
private timeResolver: TimeResolver,
private resolverA: ResolverA,
private messageService: MessageService) {
}
ngOnInit(): void {
// other UI initialization code
this.initData();
}
private initData() {
let reasons = this.resolverA.reasons; //UNDEFINED!
console.log("Reasons:", reasons);
}
}
問題是,這個ResolverA被實例化了兩次(並且只解析了在一個例子中)。第二個實例(即注入組件)具有未解析的數據。事實上,第二例應該不存在,解析器應該是單身。在這種情況下
控制檯輸出:
Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
Resource NEW
Resource RESOLVE
Resource NEW //THIS SHOULDN'T BE HERE
Reasons: undefined
Reasons: undefined
按預期工作在角2.1.2但不是在角2.2.4。 Typescript版本:2.0.10
我的代碼有問題嗎(自從角度2.2以來發生了變化)或者它被認爲是Angular中的一個錯誤?
感謝。我將暫時將路由器恢復到3.1.1。 –