Angular2 - 服务没有在构造函数和ngOnInit之外定义?

时间:2017-01-18 20:38:06

标签: angular angular2-services angular2-components

我必须在这里做错事,但我不知道是什么......我是一个Angular2新手在我的第一个ng2应用程序中磕磕绊绊。

我正在尝试从组件内访问服务上的方法,但该服务仅在构造函数()和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();
        }
    }
}

1 个答案:

答案 0 :(得分:5)

这是你传递函数的方式

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不会指向您当前的类,而是指向可观察的地方(从其所在的位置)