此问题通常出现在跨域请求中或在请求被阻止的情况下。为了解决这个问题,您可以尝试在请求头中添加Access-Control-Allow-Origin:
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch';
@Injectable() export class DataService { constructor(private http: Http) {}
getData(): Observable { return this.http.get('https://example.com/data') .map((res: Response) => res.json()) .catch((error: any) => Observable.throw(error.message || 'Server error')); } }
请注意,如果您使用CORS(跨来源资源共享),那么您需要确保服务器允许从您访问的来源接收请求。如果这不是问题,请考虑使用代理服务器或其他转发器来避免跨域问题。