[英]Angular6 / AWS Amplify - Subscribe() cannot catch error from fromPromise()
I am currently building a Web app based on Angular6 and using AWS Amplify to call the API. 我目前正在构建基于Angular6的Web应用程序,并使用AWS Amplify调用API。
USE CASE: In the component, submitForm
function calls updateProduct
function from the service. 用例:在组件中,
submitForm
函数从服务中调用updateProduct
函数。 This call returns an error. 该调用返回错误。
ISSUE: At the service level, in updateProduct
function I am able to catch the error (all good), but at the component level, I cannot catch the error. 问题:在服务级别,在
updateProduct
函数中,我能够捕获到错误(都很好), 但是在组件级别,我无法捕获到错误。
QUESTION: Why? 问题:为什么? What am I doing wrong?
我究竟做错了什么?
Here the code 这里的代码
The service: 服务:
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);
}));
}
}
The component 组件
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');
}
}
}
And the console log: Console log 和控制台日志: 控制台日志
如果要在组件级别捕获错误,请在服务中跳过捕获,或者在捕获之后继续抛出 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.