我刚刚开始使用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