After making a call to the authentication service method that checks the validity of the username and password, as well as providing an authentication token, I encountered an issue. When attempting to display the value obtained from calling the getAuthData method, it consistently showed the default/invalid value for authData.status - false.
Curiously, when I rendered the value in my template view using {{authData.status}}, it displayed the correct value after form submission. Despite extensive research through Google and documentation, I have not been able to resolve this mystery. Do I need to subscribe to service changes or is there something crucial that I am overlooking?
The problem seems to stem from the authSubmit() method in admin.component.ts
admin.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AdminComponent } from './admin.component';
import { AuthService } from '../shared/auth/index';
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [AdminComponent],
exports: [AdminComponent],
providers: [AuthService]
})
export class AdminModule { }
auth.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
export class AuthData {
public status: boolean;
public token: string;
public constructor(initStatus: boolean = false, initToken: string = '') {
this.status = initStatus;
this.token = initToken;
}
}
@Injectable()
export class AuthService {
public authData: AuthData;
public constructor(public http: Http) {
this.authData = new AuthData();
}
public getAuthData(user: string, pass: string): Observable<AuthData> {
return this.http.get('http://api.dev/auth?user=' + user+ '&pass=' + pass)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Error'));
}
}
admin.component.ts
import { Component } from '@angular/core';
import { AuthService, AuthData } from '../shared/index';
@Component({
moduleId: module.id,
selector: 'my-admin',
templateUrl: 'admin.component.html',
styleUrls: ['admin.component.css']
})
export class AdminComponent {
public authUser: string;
public authPass: string;
public authData: AuthData;
public constructor(public authService: AuthService) {
this.authData = this.authService.authData;
}
public authSubmit(): boolean {
this.authService.getAuthData(this.authUser, this.authPass)
.subscribe(
data => this.authData = data,
err => console.log(err)
);
// alert result: authData.status = false | should be: true
alert('authData.status= ' + authdata.status);
return false;
}
}
admin.component.html
<form *ngIf="!authData.status" (submit)="authSubmit()">
<input [(ngModel)]="authUser" type="text">
<input [(ngModel)]="authPass" type="password">
<button type="submit">Sign In</button>
</form>
authData.status = {{authData.status}}