Search code examples
angulartypescriptangular2-services

Angular typescript pass service function


I have two methods in my service which do very simillar things, so the subscribtion is the same. I wanted to join exection so when firing my service method

this.createNewUser(this.userModel, this.userDefaultGroupSelectedId)
            .subscribe(
            res => {
                this.msgs = ({ severity: "success", summary: "Success:\n", detail: res });
                this.userModel = new User();
                this.onConfirm.emit();
            },
            error => {
                this.msgs = ({ severity: "error", summary: "Error Message:", detail: error.Message ? error.Message : error.toString() });
            }

it would call createNewUser which shold return which function should be called

createNewUser(user: IUser, userDefaultGroupSelectedId: number): Observable<string> 
    {
        if (this.asRegistration == false) {
            return this.userAdministrationService.addNewUser(this.userModel, this.userDefaultGroupSelectedId);
        }
        else {
            this.userAdministrationService.registerNewUser(this.userModel);
        }
    }

but this approach does not work, I got Cannot read property 'subscribe' of undefined

my services:

addNewUser(user: IUser, userDefaultGroupSelectedId: number): Observable<string> {

    return this.http.post(this.addNewUserUrl)
        .catch(error => super.handleError(error))
        .map(response => response.json());
}

registerNewUser(user: IUser): Observable<string> 
{

    return this.http.post(this.registerNewUserUrl)
        .catch(error => super.handleError(error))
        .map(response => response.json());
}

Solution

  • The problem seems to be that you are not returning the result of this.userAdministrationService.registerNewUser(this.userModel);, so the return of the function in this case is undefined.

    Try changing it to:

    return this.userAdministrationService.registerNewUser(this.userModel);