这里是我的代码。
import { injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/catch';
@Injectable({
providedIn: 'root'
})
export class PostsService {
private url = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http : Http ) { }
getPosts {
return this.http.get(this.url);
}
deletePost(id) {
return this.http.get(this.url + '/' + id);
}
}
我做我的电脑它的工作,但没有工作在笔记本电脑上运行此代码。这似乎可笑,但是这是事实。 这是我的项目的结构
rxjs的新版本不再支持单一的进口,而不是尝试:
import { catchError } from 'rxjs/operators';
在角6个RXJS进口已经改变,运营商必须以管“包装”(),并没有在一开始就写点(是:.MAP,.retry,.catch;现在:地图,重试和catchError而不是抓):
import { catchError, map } from 'rxjs/operators';
并使用配管()
getPosts() {
// pack in "pipe()"
return this.http.get(this.url).pipe(
// eg. "map" without a dot before
map(data => {
return data;
}),
// "catchError" instead "catch"
catchError(error => {
return Observable.throw('Something went wrong ;)');
})
);
}
“我做这个代码我的电脑它的工作,但没有工作的一台笔记本电脑” - 在笔记本电脑上,你已经角CLI的新版本。它产生的角6用新的,其他进口。问候
在角7,在这里是如何在一个干净的方式将HTTP GET请求处理
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError, retry} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
constructor(private _http: HttpClient) {
}
public getPosts(): Observable<Post[]> {
return this._http.get(<URL>).pipe(
retry(1), catchError(error => {
return throwError(error.message);
}));
}
}
试试这个,将工作!...
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
.get(<URL>).pipe
(
catchError((error: HttpErrorResponse) =>{
return throwError(error.message || 'server error');
})
)
你为什么不尝试添加“导入‘rxjs /添加/运营/捕获’;” (把“S”,并使其运营商),而不是“进口‘rxjs /添加/运营/捕获’;”