我目前正在基于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