如何从http.get创建对象数组

时间:2019-01-19 17:35:04

标签: arrays angular http object

我有http.get,对我来说,创建对象数组是不可能的。你能帮助我吗 ?我需要在返回的对象数组上创建循环,而我无法做到这一点。

export class Link {
  idStat: String;
  idAccount: String;
}

links: Link [];

router.get('/linkGetAll', function(req, res, next) {
  Link.find(function (err, products) {
  if (err) return next(err);
    res.json(products);
  });
});

getAllLinks(){
  return this.http.get('/main/linkGetAll');
}

 this.api.getAllLinks().subscribe((data) => {
  this.links = data;
})

for(let item in this.links)
{
  DOESN'T WORK
}

2 个答案:

答案 0 :(得分:0)

String API = "https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=pageimages&format=json&pithumbsize=500&utf8";

    //open connection with wikipedia.
    HttpURLConnection httpcon = (HttpURLConnection) new URL(API).openConnection();

    //read all the input from wikipedia.
    BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
    String responseSB = in.lines().collect(Collectors.joining());
    in.close();
    JSONObject incomingJSON = new JSONObject(responseSB);

  Map<String,JSONObject> map =  (Map<String, JSONObject>) incomingJSON.getJSONObject("query").getJSONObject("pages");

  map.forEach((k,v)->{
      System.out.println(" The key is : "+k+" the title is : "+v.getString("title"));  

      //use try catch to get source because you will not get the same response every time

      String source = v.getJSONObject("thumbnail").getString("source");
  });


}

前往

之前

getAllLinks(){ return this.http.get('/main/linkGetAll') .pipe(map(res => { // do something here // res.forEach() or res.map() return 'it'; }) ); }

确保this.links中包含数据。(将async / await与toPromise()一起使用)

答案 1 :(得分:0)

请阅读this section关于Angular教程的HTTP和Angular API

get方法接受类型:

get<T>(...): Observable<T>

因此您可以修改getAllLinks的实现:

getAllLinks(): Observable<Link[] {
    return this.http.get<Link[]>('/main/linkGetAll');
}

现在,您应该应该可以迭代响应:

getAllLinks().subscribe(links => {
    links.forEach(link => // do what you need);
}