Angular 6 - 属性'subscribe'在类型"运算符函数<{}, {}>?



我用Angular 6创建了一个新项目,但当我尝试添加http请求时,会收到.subscribe错误。我只能找到以前版本的Angular的解决方案。有人能帮忙吗?

产品服务

import {Injectable} from "@angular/core";
import {Http,Response} from "@angular/http";
import {Observable} from "rxjs";
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class ProductService {
constructor(public http: Http) { }
public getProducts(dataURL:string){
return this.http.get(dataURL)
.pipe(map((res:Response) => res.json())),
catchError((error:any) => Observable.throw(error || 'Server error'));
}
}

category.component.ts

import { Component, OnInit } from '@angular/core';
import {ProductService} from "../../services/products.service";
import {Product} from "../../model/product";
import {CartService} from "../../services/cart.service";
import {Router} from "@angular/router";
@Component({
selector: 'app-category',
templateUrl: './category.component.html',
styleUrls: ['./category.component.css']
})
export class CategoryComponent implements OnInit {
public products:Array<Product>;
private sub;
constructor(
private productService:ProductService,
private cartService:CartService,
private router: Router
) { }
ngOnInit() {
this.load();
}
load = () => {
this.sub = this.productService.getProducts('./assets/mock-data/products.json')
.subscribe(res => {
this.products = res;
})
};
addToCart = (product) => {
this.cartService.addToCart({product,quantity:1})
};
ngOnDestroy() {
this.sub.unsubscribe();
}
}

pipe函数内移动catchErrorcatchError是一个rxjs运算符。操作员需要包装pipe函数才能使用它。

return this.http.get(dataURL)
.pipe(
map((res:Response) => res.json()),
catchError((error:any) => Observable.throw(error || 'Server error'))
),

最新更新