user12250118
user12250118

Reputation:

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]. Default value is Not showing, because OnInit executes before API response actually gets data. Thus dropdown is left with blank default item .

Article belows says to use map, but we are creating API proxies from Net Core Swagger. 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? Open to anything. Should I use ToPromise()? I see as option below,

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

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

}

enter image description here

Appendix: GetProductAll Proxy Code

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

Upvotes: 0

Views: 817

Answers (2)

MoxxiManagarm
MoxxiManagarm

Reputation: 9134

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>

Upvotes: 0

Gaurang Dhorda
Gaurang Dhorda

Reputation: 3387

check this stackblitz for reference StackBlitz Link

here, you have to use map inside pipe operator of rxjs.

  • In Service.ts file

    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. like this.

     ngOnInit(){
         this.dataService.getAllData().subscribe( (data) => {
               console.log('server data' + data);
               this.serviceData = data;
         }) 
     }
    
  • In your Html Template file

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

Upvotes: 0

Related Questions