簡體   English   中英

如何從 Angular 9 中的組件訪問服務類中定義的變量?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM