【问题标题】:Angular2 - service not defined outside of constructor and ngOnInit?Angular2 - 服务没有在构造函数和ngOnInit之外定义?
【发布时间】:2017-06-03 09:32:03
【问题描述】:

我一定在这里做错了什么,但我不知道是什么...我是一个 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();
        }
    }
}

【问题讨论】:

    标签: angular angular2-services angular2-components


    【解决方案1】:

    这是你传递函数的方式

    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 不会指向您当前的类,而是指向可观察对象的某个位置(从它被调用的地方)

    【讨论】:

    • 谢谢!实际上我在一秒钟前刚刚尝试了箭头功能并且它有效,但我不确定为什么。在你对 observable 发表评论后,我明白了。在两天内为某事挣扎总是很有趣,然后在公开发布问题几分钟后意识到这是一个愚蠢的错误...... :-)
    • 发布问题有助于对问题进行不同的思考,而不是在几个小时之前没有工作:D。这对找到解决方案很有帮助。
    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2019-08-30
    • 2013-10-12
    • 2021-11-27
    • 2018-01-14
    • 2016-06-16
    相关资源
    最近更新 更多