Angular 2 Http Post发送两个ajax调用而不是一个

时间:2016-03-20 19:21:38

标签: angular

您好我正试图围绕角度的可观察模式实现,我似乎遇到了某些问题。这是我的代码:

 import 'rxjs/Rx';
import {Injectable, EventEmitter} from 'angular2/core';
import {Http, Response, RequestOptions, Headers, URLSearchParams} from 'angular2/http';
import {Observable} from 'rxjs/Observable'
import {GuidService} from './guid.service';

@Injectable()
export class HttpService {
    private http: Http;
    private guidService: GuidService;
    public ajaxStarted: EventEmitter<string> = new EventEmitter();
    public ajaxCompleted: EventEmitter<string> = new EventEmitter(); 

    constructor(http: Http, guidService: GuidService) {
        this.http = http;
        this.guidService = guidService;
    }

    public post(url: string, model: any): Observable<Response> {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        //Create unique id for each ajax call
        let httpCallId = this.guidService.new();

        //Let Loading Box components that an ajax call has been triggered
        this.ajaxStarted.emit(httpCallId);

        let httpPost = this.http.post(url, JSON.stringify(model), options);

        //Let Loadinc Box Component know that ajax call has been completed
        httpPost.subscribe(success => this.ajaxCompleted.emit(httpCallId), error => this.ajaxCompleted.emit(httpCallId));

        return httpPost;
    }

}

这是我在代码表单上调用的代码:

@Component({
    selector: 'register',
    templateUrl: './app/account/components/register.view.html',
    directives: [ROUTER_DIRECTIVES]
})
export class RegisterComponent {
    private accountDataService: AccountDataService

    public registerViewModel: AccountViewModel.UserRegistrationViewModel;

    constructor(accountDataService: AccountDataService) {
        this.accountDataService = accountDataService;
        this.registerViewModel = <AccountViewModel.UserRegistrationViewModel>{};
    }

    public register() {
        this.accountDataService.register(this.registerViewModel).subscribe(x => {
            console.log(x);
        })
    }
}     

<form (ngSubmit)="register()" #userRegistrationForm="ngForm">
            <div class="form-group">
                <input class="form-control" 
                       type="email" 
                       placeholder="Email Address"
                       [(ngModel)]="registerViewModel.userName" />
            </div>
            <div class="form-group">
                <input class="form-control" 
                       type="password" 
                       placeholder="Password"
                       [(ngModel)]="registerViewModel.password" />
            </div>
            <div class="form-group">
                <input class="form-control" 
                       type="password" 
                       placeholder="Password Confirmation"
                       [(ngModel)]="registerViewModel.confirmPassword" />
            </div>
            <div class="form-group">
                <button type="submit" 
                        class="btn btn-fluid btn-primary"
                        [disabled]="!userRegistrationForm.form.valid">Register</button>
            </div>
        </form>

现在我的问题是,当我单击提交按钮而不是一个ajax调用以发送到服务器时。我已经通过在服务器上放置一个制动点并且两个呼叫到达来检查这一点。

只有在点击按钮时才会调用注册函数。

我注意到我的问题就在这一行:

  httpPost.subscribe(success => this.ajaxCompleted.emit(httpCallId), error => this.ajaxCompleted.emit(httpCallId));

如果我发表评论,只有一个ajax调用被发送到服务器。

我理解observables的方式是,当可观察值发生变化时,每个订阅都会被触发。

我在这里做错了什么?

更新

这个问题显然也在get调用中复制了。我的应用程序中的所有get调用都调用了函数:

public get(url: string, model: any = {}): Observable<Response> {
    let httpCallId = this.guidService.new();

    this.ajaxStarted.emit(httpCallId);

    let httpGet = this.http.get(url, new RequestOptions({
        headers: this.getHttpHeaders(),
        search: this.createURLSearchParams(model)
    }));

    httpGet.subscribe(success => this.ajaxCompleted.emit(httpCallId), error => this.ajaxCompleted.emit(httpCallId));

    return httpGet;
}

1 个答案:

答案 0 :(得分:5)

我猜您订阅了两次POST observable,因为您在post的{​​{1}}方法中订阅了一次并返回它。您可能会在应用程序的另一部分中再次订阅此返回的observable:

HttpService

由于默认情况下observable是冷的,相应的请求将被执行两次(如果订阅两次)。