Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Injectable()
- export class AuthService {
- private url ='http://localhost:3000/user/1';
- constructor(private http: Http){}
- isLoggedIn: boolean = false;
- user : User;
- errorMessage:any;
- login(username:string, password:string) {
- this.getUser(username, password).subscribe((user)=>{
- if(user.login===username && password===user.password){
- this.isLoggedIn=true;
- }
- })
- }
- logout(): void {
- this.isLoggedIn = false;
- }
- getUser(username:string, password:string): Observable<User>{
- return (this.http.get(this.url)
- .map(this.extractData)
- .catch(this.handleError))
- }
- private extractData(res: Response){
- let body = res.json();
- return body || {};
- }
- private handleError (error: Response | any) {
- // In a real world app, you might use a remote logging infrastructure
- let errMsg: string;
- if (error instanceof Response) {
- const body = error.json() || '';
- const err = body.error || JSON.stringify(body);
- errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
- } else {
- errMsg = error.message ? error.message : error.toString();
- }
- console.error(errMsg);
- return Observable.throw(errMsg);
- }
- }
- public Dologin() {
- this.message = 'Trying to log in ...';
- this.authService.login(this.model.username, this.model.password)
- .subscribe(() => {
- this.setMessage();
- if (this.authService.isLoggedIn) {
- let redirect = '/main';
- let navigationExtras: NavigationExtras = {
- preserveQueryParams: true,
- preserveFragment: true
- };
- // Redirect the user
- this.router.navigate([redirect], navigationExtras);
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement