Angular:我可以从Service获取对象,但是似乎我没有正确分配对象

时间:2018-09-08 08:45:34

标签: angular observable

组件:

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 :(得分:2)

首先,您不是从服务中调用方法,而是需要使用

this._itemsService.getDataFromService()

并且您正在异步地从API获取数据,并尝试在响应之前访问它,将console.log放置在订阅中,

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

答案 1 :(得分:0)

当然,您不会在控制台中获取数据。

因为获取数据会花费一些时间,并且当您订阅函数时,它将获取数据,因此将调用外部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);
  }