试图显示从csv中导出的rest api中的数据?

时间:2018-03-22 10:05:35

标签: angular rest csv

当我试图通过控制台显示数据时,我不会显示任何内容。我得到的消息未定义。 我正在使用角度

这是我的服务类

import { Injectable } from '@angular/core';
{HttpClient} from '@angular/common/http';
import {environment} from '../../environments/environment';
import {Observable} from 'rxjs/Observable';
import {any} from 'codelyzer/util/function';

const url = environment.apiEndpoint;

@Injectable()
export class CheckInService {

constructor(private http: HttpClient) {}

getCheckedToday(): Observable<string[]> {
return this.http.get<string[]>(url + '&id=37' + '&exportformat=csv');
}
}

这是我的组件

import { Component, OnInit } from '@angular/core';
import {CheckInService} from './check-in.service';

@Component({
selector: 'app-check-in',
templateUrl: './check-in.component.html',
styleUrls: ['./check-in.component.css']
})
export class CheckInComponent implements OnInit {

constructor(private checkinSerivce: CheckInService   ) { }

checkInArray: string[];
ngOnInit() {

this.checkinSerivce.getCheckedToday().subscribe(
  data => (
    this.checkInArray = data
  )
);
console.log(this.checkInArray);

}   }

my output

2 个答案:

答案 0 :(得分:0)

试试这个。我已更新您的代码

import { Component, OnInit } from '@angular/core';
import {CheckInService} from './check-in.service';

@Component({
selector: 'app-check-in',
templateUrl: './check-in.component.html',
styleUrls: ['./check-in.component.css']
})
export class CheckInComponent implements OnInit {
constructor(private checkinSerivce: CheckInService   ) { }

checkInArray: string[];
ngOnInit() {


this.checkinSerivce.getCheckedToday().subscribe(
  data => {
    this.checkInArray = data;
  }, err => {
   console.log('error loading data', err);
 }
);
console.log(this.checkInArray);

我怀疑问题是this.checkInArray = data;被括在圆括号中。如果有帮助,请告诉我

答案 1 :(得分:0)

订阅Observable是一个异步函数调用。您必须将执行代码放在订阅中。

&#13;
&#13;
import { Component, OnInit } from '@angular/core';
import {CheckInService} from './check-in.service';

@Component({
  selector: 'app-check-in',
  templateUrl: './check-in.component.html',
  styleUrls: ['./check-in.component.css']
})
export class CheckInComponent implements OnInit {

  constructor(private checkinSerivce: CheckInService   ) { }

  checkInArray: string[];
  
  ngOnInit() {

    this.checkinSerivce.getCheckedToday().subscribe(
      data => { // <- curly bracket here
        this.checkInArray = data;
        console.log(this.checkInArray); // <-- put your code here
      } // <- curly bracket here
    );
    console.log(this.checkInArray); // <-- this is undefined, because the subscription from the observable is fired asynchronously
  }
 }
&#13;
&#13;
&#13;