Issue
So there is simple application created with Ionic/Angular.
There is app.component.html (menu) that includes user phone:
<span *ngIf="phone">{{phone}}</span>
And app.component.ts:
public phone: string = ''
initializeApp() {
this.platform.ready().then(() => {
this.getUser()
});
}
getUser() {
if(this.auth.isLoggedIn) {
this.auth.getUser()
.subscribe(
user => {
this.phone = user.phone
}
)
}
}
AuthService:
public isLoggedIn: boolean = false
public token: string = null
getUser(): Observable<User> {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Token': this.token
})
return this.http
.get<User>(this.util.API_URL + '/user', { headers } )
.pipe(
map(
res => {
// api returns json response with 'result' object
return res['result']
}
)
)
}
The question I need to call getUser() method from app.component.ts when app launches. It's worked now, if user is logged in. But when user is not logged in, I need to call getUser() method after success user login. But I can't call AppComponent before initializeApp() from LoginComponent, for example.
So, what is right way to display user data in AppComponent?
Solution
auth.service:
export class AuthService {
private currentTokenSubject = new BehaviorSubject<string>(null); // <-- assign default value here
constructor(
private http: HttpClient,
private storage: Storage,
) {
this.getToken().then(
res => {
this.currentTokenSubject.next(res); // <-- push token to the observable
}
);
}
async getToken() {
return await this.storage.get('accessToken');
}
public get currentTokenValue(): Observable < string > {
return this.currentTokenSubject.asObservable(); // <-- return observable here
}
login(username: string, password: string) {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Basic ' + btoa(username + ':' + unescape(encodeURIComponent(password)))
})
return this.http.post<Token>(`${environment.apiUrl}/auth/signin`, {}, { headers }).pipe(
map((res: Token) => {
let token = res.token;
// store user details and jwt token in local storage to keep user logged in between page refreshes
this.storage.set('accessToken', token);
this.currentTokenSubject.next(token); // <-- also push new token here?
return token;
}));
}
logout() {
// remove user from local storage to log user out
this.storage.remove('accessToken');
this.currentTokenSubject.next(null);
}
}
Answered By - Roman Khegay
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.