Actually, I have a subject which will provide the authentication status. I have postlistcomponent which will show all the posts & in that component i have edit & delete buttons. Whenever i login after successful authentication a boolean value (true/false) is sent from auth service to postlist component. Then based on the boolean value we are allowing users to edit or delete the post.
In my case this is not happening. After successful authentication, edit and post buttons are not visible
auth.service.ts
private token : string;
private authStatusListener = new Subject<boolean>()
getToken() {
return this.token
}
getAuthStatusListener() {
return this.authStatusListener.asObservable()
}
loginUser(email : string , password : string) {
const authData : AuthData = {email : email,password : password}
this.http.post<{token: string}>("http://localhost:3000/api/user/login%22,authData)
.subscribe((response) => {
const serverGeneratedToken = response.token
this.token = serverGeneratedToken
this.authStatusListener.next(true)
})
login.component.ts
onLogin(form : NgForm) {
if(form.invalid){
return;
}
this.authService.loginUser(form.value.email,form.value.password)
form.resetForm();
}
post-list.component.ts
constructor(public postsService:PostsService,private authService : AuthService) {}
private authListenerSub : Subscription
userIsAuthenticated = false
ngOnInit(){
this.isLoading = true
this.postsService.getPosts(this.postsPerPage,this.currentPage)
this.postsService.getPostUpdateListener()
.subscribe((postData : {posts : Post[] , postCount : number}) => {
this.isLoading = false
this.posts = postData.posts
this.totalPosts = postData.postCount
})
this.authService.getAuthStatusListener().subscribe(isAuthenticated => {
this.userIsAuthenticated = isAuthenticated
})
}
post-list.component.html
<mat-action-row *ngIf="userIsAuthenticated">
<a mat-button color="primary" [routerLink]="['/edit',post.id]">EDIT</a>
<a mat-button color="warn" (click)="onDelete(post.id)">DELETE</a>
</mat-action-row>