简体   繁体   English

如何从 Angular 9 中的组件访问服务类中定义的变量?

[英]How to access a variable defined in service class from a component in Angular 9?

I am making a chat application wherein the service class after login I am setting a local variable as true.我正在制作一个聊天应用程序,其中登录后的服务类我将本地变量设置为 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 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 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Angular 7中从服务访问组件 - How to access a component from a service in Angular 7 如何在不使用Angular 4中的服务类的情况下访问或更新其他组件的变量 - how to access or update variable of other component without using service class in Angular 4 Angular 问题 - 尝试从组件中的服务访问变量 - Angular Issue - trying to Access a variable from a service in a component 来自服务的Angular 2访问组件变量,绑定到绑定到组件的另一个服务 - Angular 2 access component variable from service, that is bound to another service, which is bound to component 如何在 Angular 项目的组件上的局部变量上引用服务中的变量? - How reference a variable in Service on a local variable on component from a Angular Project? 如何以角方式将变量从一个组件访问另一个组件? - How to access variable from one component into another component in angular? 如何在 ZD18B8624A0F5F7221DA7B82365FC 组件中从 Angular 服务 class 调用 function? - How to call a function from Angular service class in angular view component? 如何将服务中定义的类用作组件? - How to use a class which is defined in a service into a component? Angular:如何直接从服务中操作组件中的@Input /局部变量? - Angular : How to Manipulate an @Input / local variable in component directly from a service? 如何从组件初始化 Angular 服务,自定义 class? - How to initialize Angular service, custom class from component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM