[英]How to access a variable defined in service class from a component in Angular 9?
我正在制作一个聊天应用程序,其中登录后的服务类我将本地变量设置为 true。 但是当我试图从另一个组件访问该变量时,它给了我一个错误的初始值。 那么该怎么办呢?
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
}
}
将值设置为本地存储更改后
isAuth = true
到
this.isAuth = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.