2016-12-04 163 views
-1

我剛剛開始使用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瀏覽器

+1

是請求'OPTIONS',另一個'POST'之一? – echonax

+0

一個是檢查服務器中的方法的選項請求。那麼實際的請求就會發生。 – Gary

回答

2

我認爲的網絡控制檯中看到你混淆了OPTIONSPOST用雙POST請求,請求

OPTIONS請求是跨來源必不可少的資源共享

的跨來源資源共享標準的作品,通過添加新的HTTP標頭允許服務器描述這組origi的ns允許使用Web瀏覽器讀取該信息。此外,對於可能導致用戶數據產生副作用的HTTP請求方法(特別是對於GET以外的HTTP方法,或對於某些MIME類型的POST方式),規範要求瀏覽器「預檢」請求,請求支持的方法從服務器獲取HTTP請求方法,然後在從服務器獲得「批准」時,使用實際的HTTP請求方法發送實際請求。服務器還可以通知客戶端「憑證」(包括Cookie和HTTP認證數據)是否應該隨請求一起發送。

編號:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

+0

你說得對,第一個請求是OPTIONS,第二個是POST – Maxime