用jsonp api调用返回json对象

时间:2017-09-04 22:05:14

标签: javascript json angular typescript jsonp

我试图读取从Angular 4上的JSONP API调用返回的json对象,但我一直在"未定义"在我尝试打印时在控制台中。

这是我的SearchService.ts文件:

import {Injectable} from '@angular/core';
import {Jsonp} from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class SearchService {
  apiRoot = 'this/is/my/api';
  results: any;
  loading: boolean;

  constructor(private jsonp: Jsonp) {
    this.loading = false;
  }

  search(term: string) {
    const apiUrl = `${this.apiRoot}?search=${term}&rows=10&callback=JSONP_CALLBACK`;
    return this.jsonp.request(apiUrl).map(results => { this.results = results.json().data
    });
  }

}

这是我用来执行搜索的search.component.ts文件:

import {Component, OnInit} from '@angular/core';
import 'rxjs/add/operator/toPromise';
import {SearchService} from '../../services/SearchService';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})

export class SearchComponent implements OnInit {

  loading = false;
  public result;

  constructor(private uniDirectory: SearchService) {
  }

  doSearch(term: string) {
    this.loading = true;
    this.uniDirectory.search(term).subscribe(results => this.result = results);
    this.loading = false;
    console.log('Result: ' + this.result);

  }

  ngOnInit() {

  }


}

如果我尝试在SearchService中打印结果(即console.log(results.json());),则打印出json对象。但是,如果我尝试在doSearch()方法中打印出相同的内容,则会打印undefined。任何建议表示赞赏。

2 个答案:

答案 0 :(得分:0)

看起来你错过了服务中的返回,map函数, 试试这个

search(term: string) {
const apiUrl = `${this.apiRoot}?search=${term}&rows=10&callback=JSONP_CALLBACK`;
return this.jsonp.request(apiUrl)
            .map(results => { 
                this.results = results.json().data;//you might not need this one
                return results.json(); //add this one
                });

}

答案 1 :(得分:0)

我设法解决了这个问题(有人最初将此作为答案发布并在我接受之前将其删除):

 this.uniDirectory.search(term).subscribe((results) => {
   this.result = results;
   console.log(this.result);
 });