Dogan UGUR
Dogan UGUR

Reputation: 31

why the observable item value isn't being displayed in html template

I have created a simple list-details sample with Angular4. In details page i couldn't display the item details which has Observable type class. Copying below the code block.

@Component({
  selector: 'app-user-detail',
  template: `
  <h2>User Details</h2>
  <div *ngIf="user$ | async as user; else elseBlock">
      <h3>{{user$.name.first }}</h3>
      <p>
      <button (click)="goBack()">Back</button>
      </p>
  </div>
  <ng-template #elseBlock>Undefined data</ng-template>
  `,
  styleUrls: [ './user-detail.component.css' ]
})
export class UserDetailComponent implements OnInit {
  user$: Observable<User>;

  constructor(
    private userService: UserService,
    private route: ActivatedRoute,
    private location: Location
  ) {}

  ngOnInit(): void {
     this.user$ = this.route.paramMap
      .switchMap((params: ParamMap) => this.userService.getUser(params.get('email')));
     // .subscribe(function(x) { console.log(x); });

  }

  goBack(): void {
    this.location.back();
  }
}

When i check the user$ object with the following code block i can see in console log that it retrieves user data successfully.

  this.route.paramMap
      .switchMap((params: ParamMap) => this.userService.getUser(params.get('email')));
      .subscribe(function(x) { console.log(x); }); 

But i couldn't display the user data on html template.

Upvotes: 1

Views: 557

Answers (2)

Dogan UGUR
Dogan UGUR

Reputation: 31

The reason for not displaying data on html template is related with my service calling function. this.userService.getUser(params.get('email')). params.get('email') returns email with ":" string so the service is not able to query the expected data. Just replaced ":" with empty string it worked

Upvotes: 0

cartant
cartant

Reputation: 58400

It's because, inside the h3, you refer to the user$ property, which is an observable.

You need to use the local variable, user, instead:

<div *ngIf="user$ | async as user; else elseBlock">
    <h3>{{ user.name.first }}</h3> <!-- use user here, not user$ -->
    <p>
    <button (click)="goBack()">Back</button>
    </p>
</div>

Upvotes: 1

Related Questions