在用API中的数据填充我的下拉菜单时遇到了一些问题。我需要帮助找出我做错了什么,因为我在控制台中没有得到任何错误。
Service.ts方法调用:
@Injectable({
providedIn: 'root'
})
export class OrderExceptionReportService extends ApiServiceBase {
private apiRoute: string = 'exception-report';
public sessionData: ExceptionReportSessionData[];
constructor(http: HttpClient, configService: ConfigService) {
super(http, configService);
}
public async GetExceptionReportSessionData(): Promise<ExceptionReportSessionData[]> {
if (!this.appSettings) {
this.appSettings = await this.configService.loadConfig().toPromise();
}
return await this.http.get<ExceptionReportSessionData[]>(this.appSettings.apiSetting.apiAddress + this.apiRoute + '/session-data')
.pipe(
retry(1),
catchError(this.handleError)
)
.toPromise()
}
}component.ts文件:
@Component({
selector: 'app-order-exception-report',
templateUrl: './order-exception-report.component.html',
styleUrls: ['./order-exception-report.component.scss']
})
export class OrderExceptionReportComponent implements OnInit {
public sessionData: ExceptionReportSessionData[];
constructor(private orderExceptionReportService: OrderExceptionReportService) {
}
getExceptionReportSessionData() {
this.orderExceptionReportService.GetExceptionReportSessionData()
.then(
data => {
this.sessionData = data;
});
}
ngOnInit() {
}
}我需要数据的html:
<div class="input-group">
<select class="custom-select" id="inputGroupSelect01">
<option value="" *ngFor="let session of sessionData">{{session.SessionName}}</option>
</select>
</div>Interface.ts文件:
export interface ExceptionReportSessionData {
SessionName: string,
ReportFiles: Array<string>
}发布于 2020-06-04 05:26:50
从您的评论中可以看出,this.configService.loadConfig()似乎也返回了一个HTTP observable。
在这种情况下,您可以避免使用promises,并使用RxJS方法iff来检查是否定义了this.appSettings变量,并在检索到appSettings后使用switchMap操作符切换到目标请求,从而简化流程。
请尝试以下操作
public GetExceptionReportSessionData(): Observable<ExceptionReportSessionData[]> {
return iff(() =>
this.appSettings,
of(this.appSettings),
this.configService.loadConfig().pipe(tap(appSettings => this.appSettings = appSettings))).pipe(
switchMap(appSettings => this.http.get<ExceptionReportSessionData[]>(appSettings.apiSetting.apiAddress + this.apiRoute + '/session-data')),
retry(1),
catchError(this.handleError)
);
}tap运算符用于提取结果并将其存储到this.appSettings变量中。of方法用于发送this.appSettings的可观测值,因为switchMap运算符需要一个可观测值。
然后,您可以订阅组件中的函数
export class OrderExceptionReportComponent implements OnInit {
public sessionData: ExceptionReportSessionData[];
constructor(private orderExceptionReportService: OrderExceptionReportService) {}
getExceptionReportSessionData() {
this.orderExceptionReportService.GetExceptionReportSessionData().subscribe(
data => { this.sessionData = data; },
error => { }
);
}
ngOnInit() {
this.getExceptionReportSessionData();
}
}https://stackoverflow.com/questions/62182547
复制相似问题