【问题标题】:How to access a variable defined in service class from a component in Angular 9?如何从 Angular 9 中的组件访问服务类中定义的变量?
【发布时间】:2020-08-25 16:41:24
【问题描述】:

我正在制作一个聊天应用程序,其中登录后的服务类我将局部变量设置为 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
  }

}

【问题讨论】:

  • this.auth.isAuth 是异步分配的。当您从其他组件访问它时,它尚未分配 true

标签: angular mean-stack mern web-frontend


【解决方案1】:

将值设置为本地存储更改后

isAuth = true

this.isAuth = true

【讨论】:

    猜你喜欢
    • 2020-05-02
    • 2020-11-27
    • 2017-03-07
    • 1970-01-01
    • 2019-09-11
    • 2020-07-10
    • 2020-09-17
    • 2016-12-16
    相关资源
    最近更新 更多