Angular/JavaScript amateur here, working on my first project using this framework. I have a Component that uses a Service which performs a GET request to a given URL.
Component:
@Component({
selector: 'jive-list',
templateUrl: './jivelist.component.html',
styleUrls: ['./jivelist.component.css']
})
export class JiveListComponent implements OnInit {
JiveLists: String[]; //placeholder
constructor(private JiveListService: JiveListService) { }
getJiveList(): void {
console.log("test");
this.JiveListService.getData().subscribe(
data => console.log(JSON.stringify(data)));
}
ngOnInit() {
this.getJiveList();
//console.log(this.JiveLists) //placeholder
}
}
Service:
@Injectable()
export class JiveListService {
API_URL = environment.JIVEAPIURL //can append endpoints where needed
constructor (public http: HttpClient) {
console.log("constructor runs");
}
getData(): Observable<any> {
return this.http.get<any>(this.API_URL).map((res) => res);
}
}
The API URL is a local file for now, located at './assets/data/data.json'
This code essentially gets a JSON from the URL and logs it in the console. When the file is purely JSON, this works with no issues. However, the JSON that will be provided in production always starts with a string.
JSON sample:
throw 'allowIllegalResourceCall is false.';
{
"id" : "123456",
"resources" : {
//rest of the JSON
I have tried the two solutions recommended in this article, but none of them have changed my result.
Example (attempted) solution:
getData(): Observable<any> {
return this.http.get<any>(this.API_URL).map((res) => res.substring(res.indexOf('{')));
}
My error message:
SyntaxError: Unexpected token h in JSON at position 1 at Object.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.bundle.js:43048:37) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2513:31) at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:75481:33) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2512:36) at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.bundle.js:2280:47) at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.bundle.js:2587:34) at invokeTask (http://localhost:4200/polyfills.bundle.js:3628:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.bundle.js:3654:17)
Any ideas that would help me fix this issue would be appreciated. I am using Angular 4.2.4, and using @Angular/common/HttpClientModule as my HTTP handler.