Angular6 / AWS Amplify-Subscribe()无法捕获fromPromise()的错误

时间:2018-06-20 00:59:30

标签: angular aws-amplify

我目前正在基于Angular6构建Web应用程序,并使用AWS Amplify调用API。

使用案例:在组件中,submitForm函数从服务中调用updateProduct函数。该调用返回错误。

问题: 在服务级别,通过updateProduct函数,我可以捕获错误(都很好),但是在组件级别,我不能捕获错误。

问题:为什么?我在做什么错了?

代码在这里

服务:

import { Injectable } from '@angular/core';
import { AmplifyService } from 'aws-amplify-angular';
import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(
    private amplifyService: AmplifyService
  ) { }

...

  public updateProduct(product: any): Observable<any> {
    const myInit = {
      body: product
    };
    return fromPromise(this.amplifyService.api().post('dev-myapi', '/product/' + product.id, myInit)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log('ERROR API', error.response);
      }));
  }

}

组件

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { ProductService } from '../../../services/product.service';

@Component({
  selector: 'app-product-edit',
  templateUrl: './product-edit.component.html',
  styleUrls: ['./product-edit.component.css']
})
export class ProductEditComponent implements OnInit {
    @Input() product: any;
    public myForm: FormGroup;

  constructor(
    private _formBuilder: FormBuilder,
    private productService: ProductService
  ) { }

  ngOnInit() {
    this.createForm();
  }

...

  submitForm(product: any, isValid: boolean) {
    if (isValid) {
      // Add Product ID
      console.log(this.product);
      product.id = this.product.id;
      product.type = this.product.type;
      this.productService.updateProduct(product)
        .subscribe(
          data => {
            console.log('UPDATE SUCCESS', data);
          },
          error => {
            console.log('ERROR', error);
          }
        );
    } else {
      console.log('Form is not valid');
    }
  }
}

和控制台日志: Console log

1 个答案:

答案 0 :(得分:0)

如果您想在组件级别捕获错误,请在服务中跳过捕获,或者在捕获之后继续进行throw