2016-12-04 162 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