0

User.component.ts

 user:User;

  constructor(private authService:AuthService) {}

  ngOnInit(): void {
    this.authService.user.subscribe((userVal) => {
      this.user = userVal;
      console.log(this.user);
    });
  }

User.component.html

<div class="container mt-3 ">
    <app-user-detail [userData]="user"></app-user-detail>
</div>

User.detail.component.ts

export class UserDetailComponent implements OnChanges {
  @Input() userData: User;

  constructor() {}

  ngOnChanges() {
    console.log(this.userData)
  }

}

Getting the value of "this.user" in User.component.ts but getting undefined in User.detail.component.ts

Why is that?

Lajos Bela
  • 49
  • 6
  • This is answered here https://stackoverflow.com/questions/49662341/how-to-pass-observable-value-to-input-angular-4 – MBB Jul 28 '21 at 19:00
  • Answer no 1. of top answer doesnt work which is what I want to work, ngOnChanges(changes) are undefined " userData: SimpleChange currentValue: null firstChange: true previousValue: undefined" Answer no 2. obviosly works since its a duplication of the code in the parent but that would be ugly id rather not use that – Lajos Bela Jul 29 '21 at 08:50
  • You may have add the service code as well. I believe you need to have BehaviorSubject. A sample stackblitz here - https://stackblitz.com/edit/angular-ivy-3mycyd?file=src%2Fapp%2Fapp.component.ts – MBB Jul 29 '21 at 14:58

1 Answers1

1

Try this:

[userData]="user | async"

and if it alone doesn't work, add these changes:

get user(){
return this.authService.user;
}

constructor(private authService:AuthService) {}

  ngOnInit(): void {
}
<div class="container mt-3 ">
    <app-user-detail [userData]="user | async"></app-user-detail>
</div>
  • Doesn't work, still getting the same undefined in UserDetailComponent either way. Btw This.authService.user is a Subject in authService – Lajos Bela Jul 29 '21 at 08:40