Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用可观察对象在Angular2中进行嵌套服务调用?_Angular_Typescript_Rxjs_Observable_Rxjs5 - Fatal编程技术网

如何使用可观察对象在Angular2中进行嵌套服务调用?

如何使用可观察对象在Angular2中进行嵌套服务调用?,angular,typescript,rxjs,observable,rxjs5,Angular,Typescript,Rxjs,Observable,Rxjs5,下面是我的组件文件和服务文件。我想做的是,在成功回调上的after-verification服务方法,即在subscribe中,我想调用另一个服务方法,即signup。但是,它不起作用,显示以下错误: 之前在angular1中,如果我这样做,它将起作用,但在这里不起作用: sampleService.meth1().success(function(){ //statement1... sampleService.meth1().success(f

下面是我的组件文件和服务文件。我想做的是,在成功回调上的after-verification服务方法,即在subscribe中,我想调用另一个服务方法,即signup。但是,它不起作用,显示以下错误:

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

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

注册服务


在signup方法中,您将提供一个函数作为当时的回调函数。 您应该使用箭头函数来保持相同的上下文

signupselectedUser:用户{ this.signupService.verificationselectedUser .subscribedata=>{ 游泳{ 标题:“验证您电子邮件中发送的令牌。”, 输入:“密码”, 输入属性:{ “maxlength”:10, “自动资本化”:“关闭”, “自动更正”:“关闭” } }.thenpassword=>{ this.signupService.signuppassword .subscribedata=>{ setItem'user',JSON.stringifydata; 这个.router.navigate['dashboard']; }, error=>alerterror; } }, error=>alerterror; } 根据错误判断,无法读取undefined的属性“signup”,它看起来像是在对不存在的对象调用signup

这是正确的,您创建的闭包是.thenfunction password{…},它没有捕获周围的上下文,因此用this=窗口调用,这显然不是您想要的

见:

因此,您可以使用箭头功能轻松修复它:

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

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


使用箭头函数而不是函数它起作用了我没想到是sweetalert导致了这个问题。还有一件事,如果您能在验证成功后提供帮助,我想提示用户输入,然后在调用之前将该输入放入signup方法中。好的,在调用这个之前最容易。signupService.signuppassword。。。使用显示弹出窗口的JavaScript标准提示功能向用户请求凭据。请参见然后在注册方法中使用值
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);
    }

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