如何使用observable在Angular2中进行嵌套的Service调用?

时间:2016-09-19 11:20:01

标签: angular typescript rxjs observable rxjs5

下面是我的组件文件和服务文件。我想要做的是在其成功回调上的after verification()服务方法,即在subscribe内部,我想调用另一个服务方法,即注册()。但是,它无法正常显示以下错误:

enter image description here

以前在 angular1 中,如果我这样做,它会起作用但不在这里:

sampleService.meth1().success(function(){
            //statement1...
            sampleService.meth1().success(function(data){
            //statement2...
        }).error(function(){})
    }).error(function(){});
})

Signup.component.ts

import { Component, Input } from '@angular/core';
    import { Router } from '@angular/router';
    import {User} from '../shared/model/user';
    import {SignupService} from './signup.service';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/operator/debounceTime';
    import 'rxjs/add/operator/distinctUntilChanged';
    import 'rxjs/add/operator/switchMap';
    import 'rxjs/add/operator/toPromise';

    @Component({
        moduleId: module.id,
        selector: 'ym-signup',
        templateUrl: 'signup.component.html',
        styleUrls: ['signup.component.css'],
        providers: [SignupService]
    })

    export class SignupComponent {

        @Input()
        user = {};

        constructor(private router:Router, private signupService:SignupService) {
        }

        signup(selectedUser:User) {
            this.signupService.verification(selectedUser)
                .subscribe(data => {
                        swal({
                            title: 'Verify token sent on your Email.',
                            input: 'password',
                            inputAttributes: {
                                'maxlength': 10,
                                'autocapitalize': 'off',
                                'autocorrect': 'off'
                            }
                        }).then(function (password) {

                            this.signupService.signup(password)
                                .subscribe(data => {

                                        localStorage.setItem('user', JSON.stringify(data));
                                        this.router.navigate(['dashboard']);
                                    },
                                    error => alert(error));
                        })
                    },
                    error => alert(error));
        }


        goBack() {
            this.router.navigate(['login']);
        }
    }

Signup.service.ts

import {User} from '../shared/model/user';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import {Injectable} from '@angular/core';
import {Response} from "angular2/http";
import { Observable }     from 'rxjs/Observable';


@Injectable()
export class SignupService {

    private postUrl:string = '/api/users/signup';
    private verify:string = '/api/users/verify';
    constructor(private http:Http) {
    }

    verification(user:User):Observable<JSON> {
        let headers = new Headers({
            'Content-Type': 'application/json'
        });

        return this.http
            .post(this.verify, JSON.stringify(user), {headers: headers})
            .map(this.extractData)
            .catch(this.handleError);
    }

    signup(token:string):Observable<any> {
        let headers = new Headers({
            'Content-Type': 'application/json'
        });

        return this.http
            .post(this.postUrl, JSON.stringify({verificationToken:token}), {headers: headers})
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || { };
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

}

3 个答案:

答案 0 :(得分:3)

根据错误Cannot read property 'signup' of undefined判断,您似乎在不存在的对象上调用signup()

这是正确的,你创建的闭包为.then(function (password) { ... }),它不捕获周围的上下文this,因此用this = window调用,这显然不是你想要的。

请参阅:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

所以你可以用箭头功能轻松修复它:

.then(password => {
    this.signupService.signup(password)
        .subscribe(data => {
             localStorage.setItem('user', JSON.stringify(data));
             this.router.navigate(['dashboard']);
        }, error => alert(error));
})

答案 1 :(得分:2)

在注册方法中,您将函数作为然后的回调。 你应该像箭头一样来保持相同的上下文。

 signup(selectedUser:User) {
            this.signupService.verification(selectedUser)
                .subscribe(data => {
                        swal({
                            title: 'Verify token sent on your Email.',
                            input: 'password',
                            inputAttributes: {
                                'maxlength': 10,
                                'autocapitalize': 'off',
                                'autocorrect': 'off'
                            }
                        }).then(password => {

                            this.signupService.signup(password)
                                .subscribe(data => {

                                        localStorage.setItem('user', JSON.stringify(data));
                                        this.router.navigate(['dashboard']);
                                    },
                                    error => alert(error));
                        })
                    },
                    error => alert(error));
        }

答案 2 :(得分:-1)

使用Observable.forkJoin()运行多个并发的http.get()请求。如果任何单个请求失败,整个操作将导致错误状态。 请在下面找到代码段:

getBooksAndMovies() {
        Observable.forkJoin(
            this.http.get('/app/books.json').map((res: Response) => res.json()),
            this.http.get('/app/movies.json').map((res: Response) => res.json())
        ).subscribe(
            data => {
                this.books = data[0]
                this.movies = data[1]
            },
            err => console.error(err)
        );

getBooksAndMovies() { Observable.forkJoin( this.http.get('/app/books.json').map((res: Response) => res.json()), this.http.get('/app/movies.json').map((res: Response) => res.json()) ).subscribe( data => { this.books = data[0] this.movies = data[1] }, err => console.error(err) );