【问题标题】:Angular OnInit : Values returned from Service subscribe returns Empty blank because API has not Called yetAngular OnInit:从服务订阅返回的值返回 Empty 空白,因为 API 尚未调用
【发布时间】:2019-11-07 07:48:27
【问题描述】:

我正在尝试使用 API 调用预填充下拉列表,然后使用数组 [0] 中的第一项设置下拉默认值。默认值为不显示,因为 OnInit 在 API 响应实际获取数据之前执行。因此,下拉列表中的默认项为空白。

下面的文章说要使用地图,但我们正在从 Net Core Swagger 创建 API 代理。当我输入“地图”时,它会出错。有什么方法可以解决这个问题,我是否必须将 Map 添加到我的自动生成的代理文件中,或者是否有替代解决方案?对任何事物开放。我应该使用 ToPromise() 吗?我看到下面的选项,

Angular2 - OnInit : Values returned from Service' subscribe function does not get assigned to Component field/s

“可观察”类型上不存在属性“地图”

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);
  }

}

附录: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);
}

【问题讨论】:

  • 你能把 HTML 代码发给你吗?你服务代码:) 这样我就可以使用 obserables 和异步管道以反应方式编写代码
  • 您能展示一下您的 AddressServiceProxy getproductAll() 实现吗?
  • 嗨 @JStw 刚刚展示了它
  • 嗨 @devpato 刚刚展示了它,谢谢

标签: angular angular8


【解决方案1】:

查看此 stackblitz 以获取参考 StackBlitz Link

这里,你必须在 rxjs 的管道运算符中使用 map。

  • 在 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;
           })
     )
    

    }

  • 在component.ts文件中,必须直接使用service返回的数据。像这样。

     ngOnInit(){
         this.dataService.getAllData().subscribe( (data) => {
               console.log('server data' + data);
               this.serviceData = data;
         }) 
     }
    
  • 在您的 Html 模板文件中

     <div *ngFor="let data of serviceData ; let i=index">
           <span> {{i+1}} </span> {{data.name}}
     </div>
    

【讨论】:

    【解决方案2】:

    修正你的错误:

    this.products$ = this.addressService.getproductAll().pipe(
      map(res => res.body),
    );
    

    与

    products$: Observable<productDto[]>;
    

    在模板中

    <yourdropdown [data]="products$ | async"></yourdropdown>
    

    【讨论】:

    • 接收错误,类型“Observable”不可分配给类型“Observable”。类型“ProductFormatDto[]”缺少类型“ProductFormatDto”中的以下属性:lkProductFormatId、lastModifiedByUserId、ProductFormatCode、ProductFormatDescription 和 5 多个.ts(2322)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2021-04-27
    • 1970-01-01
    • 2019-05-27
    相关资源
    最近更新 更多