I am making a chat application wherein the service class after login I am setting a local variable as true. But when I am trying to access that variable from another component it gives me the initial value which is false. So how to go about it ?
auth.service.ts
@Injectable({
providedIn: 'root'
})
export class AuthService {
url:string = 'http://localhost:3000/api/'
public isAuth: boolean = false
login(user:User){
const api = this.url + 'signin'
return this.http.post<any>(api,user,httpOptions).subscribe(response => {
if(response.token){
localStorage.setItem('token',response.token)
isAuth = true
this.router.navigate(['chat'])
}
})
}
}
chatroom.component.ts
import {AuthService} from '../services/auth.service'
@Component({
selector: 'app-chatroom',
templateUrl: './chatroom.component.html',
styleUrls: ['./chatroom.component.css']
})
export class ChatroomComponent implements OnInit,AfterViewInit{
constructor(private auth:AuthService) { }
ngOnInit(): void {
console.log(this.auth.isAuth) //is showing me false despite logging in and setting it to true
}
}
after setting value to local storage channge
isAuth = true
to
this.isAuth = true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.