2016-12-02 70 views
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中的一个错误?

回答