我是 Angular 的新手,我陷入了困境。我似乎无法让它发挥作用,我想我只是在实现 Observable 的方式上犯了一些错误。目前我使用本地 json 文件作为数据源,但在我的主项目中我将连接到外部 API。我已经剥离了所有内容,使其尽可能基本,但仍然没有运气。
这里是campaign.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { CampaignService } from '../campaign.service';
@Component({
selector: 'app-campaign',
templateUrl: './campaign.component.html',
styleUrls: ['./campaign.component.css']
})
export class CampaignComponent implements OnInit {
$campaign: Observable<any>;
constructor(
private campaignService: CampaignService
) {}
ngOnInit(): void {
this.getCampaign();
}
getCampaign(): void {
this.campaignService.getCampaign().subscribe((data) => {
this.$campaign = data;
console.log(this.$campaign);
});
}
}
这是模板 html,campaign.component.html
<div *ngIf="($campaign | async) as campaign; else loading">
<!--this never loads-->
{{campaign.shortName}}
</div>
<ng-template #loading>
<!--this is all I see-->
Loading stuff in ngIf...
</ng-template>
<br>
<br>
<!--this works so I know the data loads and that my json file is formatted correctly-->
<p>Outside of ngIf works: {{$campaign.shortName}}</p>
这是服务,campaign.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map} from 'rxjs/operators';
const endpoint = 'assets/api.json';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable()
export class CampaignService {
constructor(private http: HttpClient) {}
private extractData(res: Response) {
let body = res;
return body || { };
}
getCampaign(): Observable<any> {
const url = endpoint;
console.log(url);
return this.http.get(url).pipe(
map(this.extractData));
}
}
感谢您花时间帮助解决此问题。
最佳答案
getCampaign(): void {
this.campaignService.getCampaign().subscribe((data) => {
this.$campaign = data;
console.log(this.$campaign);
});
}
上面将数据值分配给属性 this.$campaign
,但您已将该属性声明为可观察的。
<div *ngIf="($campaign | async) as campaign; else loading">
<!--this never loads-->
{{campaign.shortName}}
</div>
$campaign 不是可观察的,因此异步管道解析为未定义。条件始终为假。
<!--this works so I know the data loads and that my json file is formatted correctly-->
<p>Outside of ngIf works: {{$campaign.shortName}}</p>
以上之所以有效,是因为为 $campaign 分配了数据值。
<p>Outside of ngIf works: {{($campaign | async)?.shortName}}</p>
您应该始终在可观察量的模板中使用async
。
您可以通过在构造函数中分配可观察量来简化组件。
constructor(private campaignService: CampaignService) {
this.$campaign = campaignService.getCampaign();
}
或者,如果您订阅并分配数据,则不必使用async
。
<div *ngIf="campaign; else loading">
<!--this never loads-->
{{campaign.shortName}}
</div>
<p>Outside of ngIf works: {{campaign?.shortName}}</p>
关于json - Angular,使用 ngIf、async 和 Observable 等待数据准备好显示内容时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741404/