使用订阅值会弄乱 UI

Using a subscribed value messes up the UI

我有一项服务(志愿者服务)可以从 JSON 文件

中获取数据作为可观察的数据

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")
  }
}

现在我正尝试使用此数据从志愿者列表的第一个创建个人资料页面

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);

        }
      )
  }
}

现在,当我尝试在 UI 上显示志愿者的姓名时,分页中断。名称显示正确,但整个东西移到了一边。

简介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>

当我获得静态数据时,即取消注释 ngOnInit() 中的第二行,它工作正常。我想知道为什么会这样。 第一张图片显示了使用静态志愿者呈现页面时呈现的内容,第二张图片显示了来自 observable 的志愿者。

即使 .scss 文件(全局,Profile.page.scss 为空,也会发生这种情况,所以这不是问题所在。 这也不是我的数据本身的问题,因为名称呈现正确(图片中的“panda 2”)

您在控制台中遇到任何错误吗?

同时我认为你应该给volunteer一个初始值

TS:

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

并且你应该在 HTML 中使用 ngIf 检查 volunteer 是否有值并且它不为空。

HTML:

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