【问题标题】:Async data from service to Component-(return data from http POST)从服务到组件的异步数据-(从 http POST 返回数据)
【发布时间】:2017-07-24 11:34:37
【问题描述】:

我已经使用http POST请求将数据发送到后端并保存数据,还从后端返回了一个名为receiptNo的元素。

现在我在服务中有receiptNo,但我无法将其发送到调用服务的组件(无法获取从服务发送到组件的异步数据的挂起)

在组件中的订阅处出现以下错误:

“布尔”类型不存在“订阅”属性。

我的组件:

   import { Component, NgZone,OnInit } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Printer, PrintOptions, Toast } from 'ionic-native';
import {LoanService} from '../../app/services/loan.service';
import {CollectionService} from '../../app/services//CollectionService';
import { CollectpaymentsPage } from '../collection/collection.component';
import { Collection}  from '../../../../common/classes/Collection';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';



@Component({
  selector: 'page-receipt',
  templateUrl: 'receipt.html'
})
export class ReceiptPage {

  base64Image: any;
  public loan: Dictionary;
  public mobile: any;
  // public form: any;
  public amount: any;
  public collection: Collection;
  public data;
  public res;

  constructor(public navCtrl: NavController,public collectionService: CollectionService, public zone: NgZone, public params: NavParams) { 
      this.loan = params.get('loan');
      this.mobile= params.get(this.mobile);
      // this.form= params.get('form');
      this.amount= params.get('amount');
      this.collection = params.get('collectionData');


   }


   ngOnInit() {
        console.log("this is receipt collectionss page")
        console.log(this.collection)
        console.log("from receipt ts")

         // XXX check for return value and errors
          // this.collectionService.saveCollection( this.collection);

          this.collectionService.saveCollection( this.collection)
                .subscribe(result => this.data = result);
}
}
interface Dictionary {
    [ index: string ]: string
}

我的服务(collectionService):

public saveCollection(  collection: Collection) {
        console.log("Collections Form data ")
        let queryParameters = new URLSearchParams();
        let headerParams = new Headers({ 'Content-Type': 'application/json' });
       var userToken = JSON.parse(localStorage.getItem('currentUser'));
       queryParameters.set('token', userToken.token );

        let requestOptions: RequestOptionsArgs = {
            method: 'POST',
            headers: headerParams,
            search: queryParameters
        };


        console.log( collection)
        var result = collection.validate()
        console.log( result)

       if( ! result["isValid"] ){
            console.log( result["message"])
            return false;

         }


        const url = this.basePath + '/api/v1/collection';

        let headers = new Headers({ 'Content-Type': 'application/json' });
         this.http.post(url, collection , requestOptions)
            .subscribe((response: Response) => {
                console.log(response);
                let receiptNo = response.json().receiptNo;
                console.log("this is return valuevalue")
                console.log(receiptNo);
                if(receiptNo){
                    console.log("tihis is return value");
                    console.log(receiptNo)
                    return response.json();

                }
                else{
                    console.log("failedfaileffailefailed")
                    return undefined;
                }
            });



    }

【问题讨论】:

  • 使用组件代码更新您的帖子。单独的 oninit 方法不足以调试您的问题。

标签: angular asynchronous typescript ionic-framework http-post


【解决方案1】:

好的,是因为返回了Subscription,尝试使用Promise

public saveCollection(  collection: Collection): Promise<any> {
    // code
    return return this.http.post(url, collection , requestOptions)
        .toPromise()
        .then((success: Response) => {
            return 'success'
         }, (fail: any) => {
            return 'fail'
         })

this.collectionService.saveCollection( this.collection)
.then(success => console.log(success), // 'success'
    fail => console.log(fail)) /// 'fail'`

【讨论】:

  • 订阅上的错误现在消失了......但是出现了一个新错误,说-无法读取未定义的属性'订阅'
  • 嘿,我的问题解决了.....但是你能解释一下到底发生了什么
【解决方案2】:

您在返回布尔值的函数上使用了 .subscribe(),但它应该是 Observable

此代码不起作用

this.collectionService.saveCollection( this.collection)
            .subscribe(result => this.data = result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2016-08-11
    • 2015-04-21
    • 2017-11-04
    • 2020-03-21
    • 2016-11-25
    • 2015-08-15
    相关资源
    最近更新 更多