Home > Software design >  Using a subscribed value messes up the UI
Using a subscribed value messes up the UI

Time:04-18

I have a service (Volunteer Service) that gets data as an observable, from a JSON file

VolunteerService.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class VolunteerService {

  constructor(private http : HttpClient) { }
  getVolunteerDetails() : Observable<any>{;
    return this.http.get("../assets/data/Sample_data.json")
  }
}

Now I'm trying to use this data for creating a profile page from the first of a list of volunteers

ProfilePage.ts

import { Component, OnInit } from '@angular/core';
import { VolunteerService } from '../volunteer.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.page.html',
  styleUrls: ['./profile.page.scss'],
})
export class ProfilePage implements OnInit {
  volunteer : any
  //imageText : any
  constructor(private volunteerService : VolunteerService) { }
  ngOnInit() {
    this.getCurrVol() 
    //this.volunteer = { "name" : "PANDA"}
  }
  getCurrVol(){
      this.volunteerService.getVolunteerDetails().subscribe(
        (data) => {
          this.volunteer = data.volunteers[0];
          console.log(this.volunteer);

        }
      )
  }
}

Now when I try to display the volunteer's name on the UI, the page breaks. The name is displayed correctly but the whole thing moves off to the side.

profile html

<ion-header>
  <ion-toolbar>
    <ion-title>profile</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-label> NAME </ion-label><ion-item>{{this.volunteer.name}}</ion-item>
</ion-content>

When I get static data i.e uncomment the second line in ngOnInit(), it works fine. I would like to know why this is happening. The first image shows what is rendered when the page is rendered with static volunteer, the second with volunteer from the observable. static

observable

This happens even if the .scss files(global, Profile.page.scss are empty, so that's not the issue. It's also not an issue with my data itself, because the name is rendered correctly("panda 2" in the picture)

CodePudding user response:

Do you get any errors in the console?

In the mean time I think you should give volunteer an initial value

TS:

   ...
 
   export class ProfilePage implements OnInit {
      volunteer = '';
    
   ...

And you should check with an ngIf in the HTML if volunteer has a value and it is not empty.

HTML:

<ion-content>
  <ion-item *ngIf="!!volunteer">
    <ion-label> NAME </ion-label>
    <ion-text>{{this.volunteer.name}}</ion-text>
  </ion-item>
</ion-content>
  • Related