我有一個服務(志愿者服務),它從 JSON 檔案中獲取資料作為可觀察的
志愿者服務.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”)
uj5u.com熱心網友回復:
您是否在控制臺中收到任何錯誤?
同時我認為你應該給出volunteer一個初始值
TS:
...
export class ProfilePage implements OnInit {
volunteer = '';
...
如果志愿者有一個值并且它不為空,您應該檢查 HTML 中的 ngIf。
HTML:
<ion-content>
<ion-item *ngIf="!!volunteer">
<ion-label> NAME </ion-label>
<ion-text>{{this.volunteer.name}}</ion-text>
</ion-item>
</ion-content>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460325.html
