【发布时间】:2020-09-22 17:23:18
【问题描述】:
在使用 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>
}
【问题讨论】:
-
this.configService.loadConfig()返回什么?我不认为this.appSettings.apiSetting.apiAddress + this.apiRoute分配了正确的 URL。您在浏览器的网络选项卡中看到正确的响应了吗? -
@MichaelD 它返回:this.http.get
(OIDC_CONFIG_URL)。它基本上是设置 api url 的第一部分。它正在到达终点。 -
您需要先从
this.configService.loadConfig()检索值。你可以使用 RxJS 方法和操作符来做任何事情。我已经发布了答案。最好直接处理 observables 而无需转换为 Promise,因为 Angular HttpClient 也使用它。越早使用越好。
标签: html angular typescript data-binding interpolation