上下文:尝试构建一个CRUD应用程序,该应用程序从给定的输入字段读取文件,然后填充列表。
到目前为止我做了什么:
-service(products.service.ts):
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private http : HttpClient) { }
private productsUrl= 'api/products';
private handleError<T>(operation ='operation', result?: T){
return (error: any): Observable<T> =>{
console.log(error,'Operation : ${operation}');
return of (result as T);
}
}
updateProduct(product: Product): Observable<any>{
return this.http.put(this.productsUrl,product,httpOptions)
.pipe(
tap(_ => console.log(`Updated product of id ${product.id}!`)),
catchError(this.handleError<any>('updateProduct'))
)
}
addProduct(product: Product): Observable<Product> {
return this.http.post<Product>(this.productsUrl, product, httpOptions).pipe(
tap((product: Product) => console.log(`Added product with id ${product.id}!`)),
catchError(this.handleError<Product>('addProduct'))
);
}
(....)
}
我使用in-memory-service-web-api来模拟我的products.service.ts中使用的web api
接下来,使用此服务的类:
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
products : Product[] ;
selectedProduct : Product;
constructor(private productService : ProductService) { }
onSelectProduct(product){
this.selectedProduct = product;
this.productService.getProduct(2)
.subscribe(product =>console.log(product));
}
ngOnInit() {
this.getProducts();
}
save(product): void {
this.productService.updateProduct(product)
.subscribe(()=>console.log('Product saved!'))
}
add(name : string, price: number) : void {
this.productService.addProduct({name,price} as Product)
.subscribe(product =>{
this.products.push(product);
});
}
(...)
}
此外,与该类关联的模板:
(...)
<ul>
<li
class="product"
[class.selected]="selectedProduct && selectedProduct.name === product.name"
*ngFor="let product of products"
>
<input type="text" pInputText [(ngModel)]="product.name"/>
<div (click)="onSelectProduct(product)">Name : {{product.name }}</div>
<div>ID : {{product.id }}</div>
<div>Price : {{product.price }}</div>
<button (click)="save(product)" pButton type="button" label="Save" class="ui-button-success"></button>
<button (click)="delete(product.id)" pButton type="button" label="Delete" class="ui-button-raised ui-button-danger"></button>
</li>
</ul>
(...)
正如标题所示,我试图从一个可以是任何格式(不仅是JSON)的文件中读取并填充我的列表。我该怎么做?我正在努力学习Angular而且我被困住了。
也许您可以构建一个HttpInterceptor
并检查内容类型,以便您可以提供不同的响应解析?检查这个答案,因为它可以帮助你:https://stackoverflow.com/a/51491994/3811645