Angular: я могу получить объект из Service, но, похоже, я не назначил объект должным образом - PullRequest
0 голосов
/ 08 сентября 2018

Компонент:

import { Component, OnInit } from '@angular/core';
import { ItemsService } from '../items.service';
import { Observable } from 'rxjs';
import { Item } from '../item.model';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-customer',
  templateUrl: './customer-detail.component.html',
  // styleUrls: ['./customers-table.component.css'],
  providers: [ItemsService],
})
export class CustomerDetailComponent implements OnInit {
  customer: Item;
  constructor(private _itemsService: ItemsService, private route: 
ActivatedRoute) {
  }

ngOnInit() {
    console.log(this.getDataFromService().subscribe(data => 
console.log(data)));
    this.getDataFromService().subscribe(data => this.customer = data);
    console.log(this.customer);
  }

  public getDataFromService() {
    const id = +this.route.snapshot.paramMap.get('id');
    const paraid: string = String(id);
    return this._itemsService.getItem(paraid);
  }

}

Услуги:

@Injectable()
export class ItemsService {

  private BASE_URL = 'http://localhost:3000/api/';

  constructor(private http: HttpClient) { }

  // Uses http.get() to load data from a single API endpoint
  getItem(id: String): Observable<Item> {
    console.log('getItem: ' + id);
    return this.http.get<Item>(`${this.BASE_URL + id}`);
  }

Из журнала консоли я получил это:

Subscriber {closed: false, _parent: null, _parents: null, 
_subscriptions: Array(1), syncErrorValue: null, …}

[{…}]
0
:
{CustomerID: 1000, FirstName: "Suzanne", LastName: "Jones", BirthDate: 
"1999-01-01"}
length
:
1
__proto__
:
Array(0)

У меня есть элемент, который нужно получить из конечной точки API, который получит элемент по запросу SQL из базы данных. Мне удалось получить данные, как я могу console.log (data). но я не могу console.log (this.customer), я что-то не так сделал в data => this.customer = data?

Ответы [ 2 ]

0 голосов
/ 08 сентября 2018

OffCourse вы не будете получать данные в вашу консоль.

, поскольку для извлечения данных потребуется время, а когда вы подпишетесь на свою функцию, она перейдет к извлечению данных, будет вызвана ваша внешняя console.

Используйте settimeout(()=> {}, 1000) вот так:

ngOnInit() {
    console.log(this.getDataFromService().subscribe(data => 
console.log(data)));
    this.getDataFromService().subscribe(data => this.customer = data);
settimeout(()=> {  console.log(this.customer); }, 1000);
  }
0 голосов
/ 08 сентября 2018

Прежде всего, вы не вызываете метод из сервиса, вам нужно использовать

this._itemsService.getDataFromService()

и вы получаете данные из API асинхронно и пытаетесь получить к ним доступ до ответа, поместите console.log внутри подписки,

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