2017-01-18 26 views
1

我必須在這裏做錯事,但我不知道什麼......我是一個Angular2新手在我的第一個ng2應用程序中蹣跚而行。我試圖從一個組件內訪問服務的方法,但該服務只在構造函數()和ngOnInit()中定義,它返回爲我的其他組件函數中未定義的。Angular2 - 服務未在構造函數和ngOnInit之外定義?

這與this issue類似,但我使用的是private關鍵字,仍然存在問題。

這裏是我的服務:

import { Injectable } from "@angular/core"; 
import { AngularFire,FirebaseListObservable } from 'angularfire2'; 
import { User } from './user.model'; 

@Injectable() 

export class UserService { 
    userList$: FirebaseListObservable<any>; 
    apples: String = 'Oranges'; 

    constructor(private af: AngularFire) { 
     this.initialize(); 
    } 

    private initialize():void { 
     this.userList$ = this.af.database.list('/users'); 
    } 

    getTest(input:String):String { 
     return "Test " + input; 
    } 

    getUser(userId:String):any { 
     //console.log('get user',userId); 
     let path = '/users/'+userId; 
     return this.af.database.object(path); 
    } 
} 

而且我的組件:

import { Component, OnInit } from '@angular/core'; 
import { ActivatedRoute } from '@angular/router'; 
import { UserService } from '../../shared/user.service'; 

@Component({ 
    moduleId: module.id, 
    selector: 'user-detail', 
    templateUrl: 'user-detail.component.html' 
}) 
export class UserDetailComponent implements OnInit { 

    routeParams$: any; 

    one: String; 
    two: String; 
    three: String; 

    constructor(private usrSvc:UserService,private route:ActivatedRoute) { 
     console.log('constructor',usrSvc); // defined here 
     this.one = usrSvc.getTest('this is one'); // works correctly 
    } 

    ngOnInit() { 
     console.log('ngOnInit',this.usrSvc); // also defined here 
     this.two = this.usrSvc.getTest('this is two'); // also works correctly 
     this.routeParams$ = this.route.params.subscribe(this.loadUser); 

    } 

    loadUser(params:any) { 
     console.log('loadUser',this.usrSvc); // undefined!! 
     this.three = this.usrSvc.getTest('this is three'); // BOOM 
    } 

    ngOnDestroy() { 
     if (this.routeParams$) { 
      console.log('unsub routeParams$'); 
      this.routeParams$.unsubscribe(); 
     } 
    } 
} 

回答

4

這是你傳遞給函數的方式

this.routeParams$ = this.route.params.subscribe(this.loadUser); 

應該

this.routeParams$ = this.route.params.subscribe(this.loadUser.bind(this)); 

this.routeParams$ = this.route.params.subscribe((u) => this.loadUser(u)); 

否則this不指向當前的類,但在某處可觀察到的(從那裏它被稱爲)

+1

謝謝!我其實剛剛嘗試了箭頭功能,它的工作,但我不知道爲什麼。在您對可觀察的事件發表評論後,我明白了。與2天的事情鬥爭總是很有趣,然後在公開發布問題幾分鐘後意識到這是一個愚蠢的錯誤...... :-) – Josh

+0

發佈一個問題有助於很多人對這個問題有不同的想法工作時間:D。這有助於尋找解決方案。 –

相關問題