我目前正在构建一个基于 Angular6 的 Web 应用程序,并使用 AWS Amplify 来调用 API。
用例:在组件中,函数从服务submitForm
调用 函数。updateProduct
此调用返回错误。
ISSUE:在服务级别,在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');
}
}
}
和控制台日志: 控制台日志