I just start first project with Angular 2 and I've trouble with services.
I've an http service called when submitting a form, but when I submit the form, the http request is executed twice.
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);
}
I added some console.log("test");
to check which method is called twice and it appears that there is no method called twice, just the HTTP request that I can see in the network console of the web browser