Angular 6 отображает данные из остальных API через сервис - PullRequest
0 голосов
/ 01 марта 2019

Я хотел бы отобразить данные из API остальных в моем угловом компоненте.У меня есть некоторые данные из этого URL-адреса заполнителя: https://jsonplaceholder.typicode.com/posts. Я написал для него услугу следующим образом:

Service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class nowService {

  serviceApiUrl: string = 'https://jsonplaceholder.typicode.com/posts';

  constructor(
    private http: HttpClient,

    ) { }

    public title: string;
    public id: number;  
    public body: string;
    public userId: number;

  public getAll() {
    return this.http.get(this.serviceApiUrl);
  }
}

Файл component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
// Services 
import { nowService } from '../../services/now.service';


@Component({
  selector: 'app-service-incident',
  templateUrl: './service.component.html',
  styleUrls: ['./service.component.scss']
})
export class ServiceIncidentComponent implements OnInit {

  constructor(private service: nowService) {

  }

  ngOnInit() {
    this.service.getAll().subscribe((data) => {
      console.log('Result - ', data);
      console.log('data is received');
    })
  }
}

Я хочу иметь возможность отображать эти данные в таблице.

1 Ответ

0 голосов
/ 01 марта 2019

Вам нужно что-то подобное, используя ngFor,

   <table class="table table-striped">
        <thead>
            <tr>
                <th>Title</th>
                <th>Id</th>
            </tr>
        </thead>
        <tbody>
           <tr *ngFor="let user of users">
            <td>{{user.id}}</td>
            <td><a routerLink="/detail/{{user.id}}">{{user.title}}</a></td>
           </tr>
        </tbody>
    </table>
</div>

, а в компоненте ts.

вам нужно присвоить ответ обратно переменной с именем users.что-то вроде

export class ServiceIncidentComponent implements OnInit {
  users: any; //better to have your type
  constructor(private service: nowService) {

  }

  ngOnInit() {
    this.service.getAll().subscribe((data) => {
       this.users = data;
    })
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...