簡體   English   中英

如何將變量從一個組件傳遞到同一級別的另一個組件?

[英]How to pass a variable from one component to another that is at the same level?

如何將變量從一個組件傳遞到同一級別的另一個組件? 我在Auth組件服務中有用戶變量

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private user: string = null;

  getUser() {
    return this.user;
  }

  setUser(username) {
    sessionStorage.setItem('username', username);
    this.user = sessionStorage.getItem('username');
    console.log('VAMOS!!!', this.user);
  }
}

在第一個組件中,我將其注入,如果獲得用戶變量的值,則當用戶進行身份驗證時,我將使用this.router.navigate (['/ meet'])將其重定向,即,可視化下一個組件。

在下一個名為list-user的組件中,我在getUser ()得到null

async ngOnInit() {
  console.log('HOY', this.authService.getUser());
} 

當您重定向到['/ meet']時,Authservice組件將從DOM中刪除。

這就是為什么它提供null的原因。

為什么不在當前組件中使用sessionStorage.getItem?

async ngOnInit() {

    console.log('HOY',sessionStorage.getItem('username'));
}

我們可以在全球范圍內使用服務存儲數據,以便我們可以訪問任何組件中的數據。

  • 如果您在模塊級別提供服務(同一單例實例將為所有組件共享)。

  • 如果您在組件級別提供服務(新實例將
    為組件創建)。

因此,請不要根據您的用例在組件級別注入服務。

@Component({
  selector: 'a-comp',
  template: `<div></div>`
})
export class AComponent implements OnInit {
  constructor( private authService: AuthService ) {}
  ngOnInit() {
    console.log('HOY', this.authService.getUser());
  }
}

@Component({
  selector: 'b-comp',
  template: `<div></div>`
})
export class BComponent implements OnInit {
  constructor( private authService: AuthService ) {}
  ngOnInit() {
    console.log('HOY', this.authService.getUser());
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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