如何解决如何从Angular 9中的组件访问服务类中定义的变量?
我正在制作一个聊天应用程序,其中登录后的服务类是将本地变量设置为true。但是,当我尝试从另一个组件访问该变量时,它给我的初始值为false。那怎么办呢?
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。