2017-03-16 22 views
0

我有兩個服務,其中第一個是在第二業務注入,以這樣的方式服務在服務注入是不確定的

rule.service.ts

@Injectable() 
export class RuleService { 

    constructor(
     private _resourceService: ResourceService 
    ){} 

    someMethod(url: string) { 
     this._resourceService.getData(url).then((res) => { 
      console.log(res); 
     } 
    } 

} 

resource.service.ts

@Injectable() 
export class ResourceService { 

    constructor(
     http: Http 
    ) { } 

    public getData(url?: string): Promise<T> { 
     //some code 
    } 
} 

稱爲服務jQuery的:(

private run(input: any, a_parameters: any) { 
$("select[name='" + a_parameters[0] + "']").change(function(e: any) { 
      return new Promise((resolve) => { 
       let array: any[] = []; 
       this._resourceService.getData(a_parameters[1]).then(() => { 
        let result: any; 
... 

,但是當我試圖調用的someMethodRuleService,我得到這個控制檯錯誤:

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'getData' of undefined TypeError: Cannot read property 'getData' of undefined at eval (eval at (http://localhost:8099/app.js:457:2), :210:39) at new ZoneAwarePromise (eval at (http://localhost:8099/polyfills.js:2304:2), :695:29) at HTMLSelectElement.eval (eval at (http://localhost:8099/app.js:457:2), :208:20) at HTMLSelectElement.dispatch (http://cdn.execon.pl/resources/GRM/js/libs/jquery-1.11.0.min.js:3:8066) at HTMLSelectElement.r.handle (http://cdn.execon.pl/resources/GRM/js/libs/jquery-1.11.0.min.js:3:4767) at ZoneDelegate.invokeTask (eval at (http://localhost:8099/polyfills.js:2304:2), :363:31) at Object.onInvokeTask (eval at (http://localhost:8099/vendor.js:101:2), :3971:41) at ZoneDelegate.invokeTask (eval at (http://localhost:8099/polyfills.js:2304:2), :362:36) at Zone.runTask (eval at (http://localhost:8099/polyfills.js:2304:2), :166:47) at HTMLSelectElement.ZoneTask.invoke (eval at (http://localhost:8099/polyfills.js:2304:2), :416:38) ErrorHandler.handleError @ core.umd.js?e2a5:3064 next @ core.umd.js?e2a5:8041 schedulerFn @ core.umd.js?e2a5:3689 SafeSubscriber.__tryOrUnsub @ VM86162:223 SafeSubscriber.next @ VM86162:172 Subscriber._next @ VM86162:125 Subscriber.next @ VM86162:89 Subject.next @ VM86159:55 EventEmitter.emit @ core.umd.js?e2a5:3675 NgZone.triggerError @ core.umd.js?e2a5:4040 onHandleError @ core.umd.js?e2a5:4001 ZoneDelegate.handleError @ zone.js?fad3:334 Zone.runGuarded @ zone.js?fad3:142 _loop_1 @ zone.js?fad3:540 drainMicroTaskQueue @ zone.js?fad3:549 ZoneTask.invoke @ zone.js?fad3:420 ListPicker._handleMouseUp @ about:blank:540

任何人都可以告訴我,我做錯了什麼?如何更正服務中的服務?

+1

請添加你在哪裏調用代碼'someMethod' – yurzui

+0

編輯:調用方法 –

+0

謝謝:)然後我看到你失去語境 – yurzui

回答

3

您需要使用箭頭功能保留this

$("select[name='" + a_parameters[0] + "']") 
    .change((e: any) => { // <== arrow function instead of FE(function expression) 
     return new Promise((resolve) => { 
      let array: any[] = []; 
      this._resourceService.getData(a_parameters[1]).then(() => {