我剛剛開始使用Angular 2的第一個項目,並且遇到服務問題。Angular 2服務訂閱兩次
我提交表單時調用了http服務,但是當我提交表單時,http請求會執行兩次。
login.component.html
<form method="post" (ngSubmit)="login()">
<input type="email" [(ngModel)]="user.email" id="email" name="email" placeholder="Email" class="input input--block input--text-center" required >
<input type="password" [(ngModel)]="user.password" name="password" placeholder="Password" id="passord" class="input input--block input--text-center" required>
<input type="submit" value="Connect" class="btn btn--block">
</form>
login.component.ts
login() {
this.service.login(this.user.email, this.user.password)
.subscribe(res => {
if (res == null) {
alert("Fail");
} else {
res.password = null;
this.user = res;
alert("Welcome "+this.user.firstname+"!");
}
});
}
user.service.ts
login(email:string, password:string): Observable<User> {
let CryptoJS = require("cryptojs");
let sha512 = CryptoJS.algo.SHA512.create();
sha512.update(password);
password = sha512.finalize().toString();
return this.http.post(`${this.baseUrl}/user/login`,
{email: email.trim(), password: password.trim()},
{headers: this.headers })
.map(res => res.json())
.catch(this.handleError);
}
我加了一些console.log("test");
檢查哪個方法被調用兩次,似乎沒有叫兩聲方法,只是HTTP請求,我可以在Web瀏覽器
是請求'OPTIONS',另一個'POST'之一? – echonax
一個是檢查服務器中的方法的選項請求。那麼實際的請求就會發生。 – Gary