我在以下代码中遇到错误,并且我想知道哪些操作不正确。我试图从REST API中获取数据并收到此错误。
代码:
import {Injectable} from "@angular/core";
//import {POSTS} from "./mock-posts";
import { Http, Headers,RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class PostService {
posts: any;
// API LINK
GET_ALL_POST : string = 'http://xxx.xxx/get_all_posts';
constructor(public http: Http) {
this.http = http;
}
getAll() {
return this.http
.get(this.GET_ALL_POST)
.map(res => res.json());
}
}
错误:
[02:36:20] Error: Error at C:/Users/nonren/Documents/Ionic/socialtag/.tmp/services/post-service.ts:18:3
[02:36:20] Return type of public method from exported class has or is using name 'Observable' from external module
"C:/Users/nonren/Documents/Ionic/socialtag/node_modules/rxjs/Observable" but cannot be named.
[02:36:20] ngc failed
[02:36:20] ionic-app-script task: "build"
[02:36:20] Error: Error
代码I用于致电getAll()
:
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {PostService} from '../../services/post-service';
import {PostPage} from '../post/post';
import {UserPage} from '../user/user';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public posts: any;
constructor(public nav: NavController, public postService: PostService) {
this.posts = postService.getAll();postService.getAll().subscribe(
data => {
this.posts = data;
console.log(this.posts);
}
);
}
答案 0 :(得分:2)
您无法订阅Observable
两次。
如果您希望进行异步调用的方法的调用者能够订阅结果,则需要确保返回Observable
,但如果此方法调用subscribe()
,则而是返回Subscription
。
将方法更改为使用.map()
而不是subscribe()
。然后它将返回Observable
。
getServerData() {
return this.http.get(...).map(response => response.json()));
}
otherMethod() {
this.service.getServiceData().subscribe(response => this.data = response);
}