I'm trying to read a json object that is returned from a JSONP API call on Angular 4, but I keep getting "undefined" in the console when I try to print it.
This is my SearchService.ts file:
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
});
}
}
And this is the search.component.ts file that I'm using to carry out the search:
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() {
}
}
If I try and print the result in the SearchService (i.e. console.log(results.json());
), the json object is printed out. However, if I try to print out the same in the doSearch() method, then it prints undefined. Any suggestions are appreciated.