[英]Angular OnInit : Values returned from Service subscribe returns Empty blank because API has not Called yet
I am trying to Prepopulate a Dropdown list with API call, and then set Dropdown Default value with the very first item in array[0].我正在尝试使用 API 调用预填充下拉列表,然后使用数组 [0] 中的第一项设置下拉默认值。 Default value is Not showing, because OnInit executes before API response actually gets data.默认值为不显示,因为 OnInit 在 API 响应实际获取数据之前执行。 Thus dropdown is left with blank default item.因此,下拉列表中的默认项目为空白。
Article belows says to use map, but we are creating API proxies from Net Core Swagger.下面的文章说使用 map,但我们正在从 Net Core Swagger 创建 API 代理。 When I type 'map', it gives error.当我输入“地图”时,它会出错。 What is a way to solve this, do I have to add Map to my autogenerated proxy files, or is there Alternative Solution?有什么方法可以解决这个问题,我必须将 Map 添加到我的自动生成的代理文件中,还是有替代解决方案? Open to anything.对任何事物开放。 Should I use ToPromise()?我应该使用 ToPromise() 吗? I see as option below,我看到下面的选项,
Angular2 - OnInit: Values returned from Service' subscribe function does not get assigned to Component field/s Angular2 - OnInit:从服务返回的值订阅 function 未分配给组件字段
Property 'map' does not exist on type 'Observable' “可观察”类型上不存在属性“地图”
export class productDropdownComponent implements OnInit {
products: any[] = [];
@Input() productDefaultItem: productDto;
@Input() selectedproduct: any;
@Input() TxtField: string = 'productDescription';
@Input() styles:string;
@Output() selectedItemOutput = new EventEmitter();
constructor(private addressService:AddressServiceProxy, private readonly productService: productService ) { }
ngOnInit() {
this.loadproducts() ;
this.productDefaultItem = new productDto();
this.productDefaultItem = this.products[0];
}
loadproducts() {
this.addressService.getproductAll().map(res => {
this.products = res.body;
})
}
statusSelectedItemChanged(e) {
this.productService.changeMessage(e);
}
}
Appendix: GetProductAll Proxy Code附录:GetProductAll 代理代码
getProductAll(): Observable<ProductResponse> {
let url_ = this.baseUrl + "/api/Product/GetProductAll";
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Accept": "application/json"
})
};
return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processGetProductAll(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processGetProductAll(<any>response_);
} catch (e) {
return <Observable<ProductResponse>><any>_observableThrow(e);
}
} else
return <Observable<ProductResponse>><any>_observableThrow(response_);
}));
}
protected processGetProductAll(response: HttpResponseBase): Observable<ProductResponse> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = ProductResponse.fromJS(resultData200);
return _observableOf(result200);
}));
} else if (status === 500) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("Server Error", status, _responseText, _headers);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<ProductResponse>(<any>null);
}
Fixing your error:修复您的错误:
this.products$ = this.addressService.getproductAll().pipe(
map(res => res.body),
);
With和
products$: Observable<productDto[]>;
And in template在模板中
<yourdropdown [data]="products$ | async"></yourdropdown>
check this stackblitz for reference StackBlitz Link检查此 stackblitz 以获取参考StackBlitz Link
here, you have to use map inside pipe operator of rxjs.在这里,您必须在 rxjs 的 pipe 运算符中使用 map。
In Service.ts file在 Service.ts 文件中
getAllData(){ return this.http.request <any[]> ('get', "https://raw.githubusercontent.com/lewagon/flats-boilerplate/master/flats.json").pipe( map(data => { console.log('map data' + data); return data; }) )
} }
in component.ts file , You have to use data returned by service directly.在 component.ts 文件中,您必须直接使用服务返回的数据。 like this.像这样。
ngOnInit(){ this.dataService.getAllData().subscribe( (data) => { console.log('server data' + data); this.serviceData = data; }) }
In your Html Template file在您的 Html 模板文件中
<div *ngFor="let data of serviceData; let i=index"> <span> {{i+1}} </span> {{data.name}} </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.