Search code examples
angularangular2-servicesangular2-components

Angular2 - service not defined outside of constructor and ngOnInit?


I MUST be doing something wrong here, but I have no clue what... I'm an Angular2 newbie stumbling through my first ng2 app.

I'm trying to access methods on a service from within a component, but the service is only defined in constructor() and ngOnInit(), it comes back as undefined in my other component functions.

This is similar to this issue but I am using the private keyword and still having the problem.

Here's my service:

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);
    }
}

And my component:

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();
        }
    }
}

Solution

  • This is from the way you pass the function

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

    should be

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

    or

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

    otherwise this doesn't point to your current class but somewhere to the observable (from where it's called)