You can use httpClient interceptor:
The documentation link is : Angular io
Example for setting authentication header for every request:
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
EDIT:
After i got your point correctly here are what you should do:
Write a services for login:
import {Injectable} from '@angular/core';
import { HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class AuthenticationService{
constructor(private http:HttpClient){}
public isUserNameExist(username:string):Observable<boolean>{
private url:string = "Your server side url";
return this.http.get(url);
}
public login(username:string, password:string)Observable<User>{
private url:string = "";
return this.http.post<User>(url);
}
}
And in your component you can write the following:
export class loginComponent{
constructor(private authService:AuthenticationService){}
onFromSubmit(username:string, password:string){
this.authService.login(username, password)
.subscribe(user => //Do what ever you want);
}
}