Angular OnInit: значения, возвращаемые подпиской на службу, возвращают пустое поле, поскольку API еще не вызывался - PullRequest
0 голосов
/ 07 ноября 2019

Я пытаюсь предварительно заполнить раскрывающийся список с помощью вызова API, а затем установить значение по умолчанию для раскрывающегося списка с самым первым элементом в массиве [0]. Значение по умолчанию не отображается, поскольку OnInit выполняется до того, как ответ API действительно получит данные. Таким образом, в раскрывающемся списке остается пустой элемент по умолчанию.

В статье ниже говорится, что нужно использовать карту, но мы создаем прокси API из Net Core Swagger. Когда я набираю «map», это дает ошибку. Как решить эту проблему, нужно ли добавить Map в мои автоматически сгенерированные прокси-файлы или есть альтернативное решение? Открыто для всего. Должен ли я использовать ToPromise ()? Я вижу, как вариант ниже,

Angular2 - OnInit: значения, возвращаемые из функции подписки Service ', не присваиваются полю компонента / s

Property' map'не существует для типа' Наблюдаемый '

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

Приложение: прокси-код 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);
}

Ответы [ 2 ]

1 голос
/ 07 ноября 2019

проверьте этот стекаблитц для ссылки StackBlitz Link

здесь, вы должны использовать карту внутри оператора канала rxjs.

  • В файле 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;
           })
     )
    

    }

  • в компоненте.ts file , Вы должны использовать данные, возвращенные сервисом напрямую. вот так.

     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>
    
0 голосов
/ 07 ноября 2019

Исправление вашей ошибки:

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

С

products$: Observable<productDto[]>;

И в шаблоне

<yourdropdown [data]="products$ | async"></yourdropdown>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...