1

Есть в сети джейсон файл. (структура проще некуда (id:10, name:Jon). С помощью http на ангуляре 2-ом хочу получить этот файл и хотя бы первую строку вывести в {{result}}

Как это сделать?

2 ответа 2

1
 Можно вот так:
getLocation() {
    return this.http.request('/app/admin/users/driver/services/json/location.json')
        .map(res => res.json());
}

а в контроллере

 service.getLocation().subscribe(
 res => {

  console.log(res)
})

Обновлено

import {HttpService} from 'path/to/httpService'; //без расширения
 ...
@Component({
... 
template: `<p>{{ result.name }}</p>
           <p>{{ result.age }}</p>`,
providers: [Http, HttpService]
})
...
private result:any = {name: '', age:''};
constructor(private service:HttpService) {
    this.getData();
}

getData() {
   let self = this;
   this.service.getLocation()
          .subscribe(res => {
          self.result = res;
          console.log(res); 
         });
}

Пример по ссылке

1
1

Для вывода елементов в html используй директиву *ngFor:

template.html

<tr *ngFor="let element of elements">
  <td>{{ element.name }}</td>
</td>

Чтобы получить файл, отправь GET-запрос

some.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Component({
  moduleId: module.id,
  selector: 'sd-home',
  templateUrl: 'template.html'
})

@Injectable()
export class SomeComponent implements OnInit {
  public elements: any;

  constructor(
    private router: Router,
    private http: Http
  ) {}

  ngOnInit(){ this.getInfo(); }

  getInfo(){
    let resp = this.index();
    resp.subscribe(data => {this.elements = data.elements;});
  }

  index() {
    return this.http.get('http://example.com')
      .map((res: Response) => res.json())
  }
}
6

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.