如何从我的项目中使用Http.get获取数据?

时间:2016-08-02 11:39:26

标签: javascript typescript angular angular2-http

我有一个包含一些用户的ts文件:

快速启动-鼓起/应用/模拟/ user.mock.ts:

import {User} from "../user";

export const USERS:User[]=[
  new User(....);
];

一个serice - quickstart-muster / app / services / user.service.ts:

import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable"
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/toPromise';
import {Http} from "@angular/http";
import {User} from "../user";

@Injectable()
export class UserService {

  constructor(private http:Http){}

  public loadUsers():Observable<User[]>{
    return this.http.get('../mock/user.mock.ts')
      .map(res=>res.json());
  }
}

我知道那不会工作而不是,我得到404错误,说他找不到... / mock / user.mock.ts。

如何让它发挥作用?

2 个答案:

答案 0 :(得分:1)

您可以加载一个JSON文件,就像它来自API:

<强> /data.json

[
    {
        "id": 1234,
        "name": "...",
        ...
    },
    ...
]

然后你可以像这样加载它:

public loadUsers(): Observable<User[]>{
  return this.http.get('data.json')
    .map(res => res.json());
}

你也可以从头开始创建一个Observable

public loadUsers(): Observable<User[]> {
    return Observable.create((observer) => {
        observer.onNext(USERS);
        observer.onCompleted();
    });
}

答案 1 :(得分:0)

使用Promise.resolve代替http get

 public static void getProperties(String infile) throws IOException {
        final int lhs = 0;
        final int rhs = 1;

        ArrayList list = new ArrayList();
        BufferedReader  bfr = new BufferedReader(new FileReader(new File(infile)));

        String line;
        while ((line = bfr.readLine()) != null) {
            if (!line.isEmpty()) {
                String[] pair = line.trim().split(":");
                list.add(pair[rhs].trim());
            }
        }

        bfr.close();

        System.out.println(list.toString());
    }