In NativeScript, the http
module doesn't currently support making network requests to the local file system. That work is intended to be done by the file reader. It's pretty simple to read a local file and parse its contents as JSON.
This is the TypeScript/Promise version of what Emil Oberg created for the same question on StackOverflow. This module should be reusable for any and all asyncronous local JSON read operations.
import * as fs from 'file-system';
var documents = fs.knownFolders.currentApp();
class FileReader {
static readJSON(path: string) {
var jsonFile = documents.getFile(path);
return new Promise<Object>((resolve, reject) => {
try {
jsonFile.readText().then((content: string) => {
let data = <Array<Object>>JSON.parse(content);
resolve(data);
});
}
catch (err) {
reject(err);
}
});
}
}
export default FileReader;
Can someone tell me how to do this in Angular2 and Nativescript?
Here is my code:
spotify.service.ts:
`import {Injectable} from '@angular/core'
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
//import {NSHttp} from 'nativescript-angular/http';
@Injectable()
export class SpotifyService {
private artistsUrl: string = 'https://api.spotify.com/v1/search?offset=0&limit=30&market=US&query=';
private tsturl: string = 'https://api.spotify.com/v1/search?offset=0&limit=30&market=US&query=john&type=artist';
private artistUrl: string = 'https://api.spotify.com/v1/artists/';
private albumUrl: string = 'https://api.spotify.com/v1/albums/';
}`
And here is where I use it search.component.ts:
`import { Component } from '@angular/core';
import {SpotifyService} from '../../services/spotify/spotify.service';
import {Artist} from '../../types/artist';
@component({
moduleId: module.id,
selector: 'search',
templateUrl: 'search.component.html',
providers:[SpotifyService]
})
export class SearchComponent {
private srchtxt:string;
private searchRes:any[];
private searchResStr:string;
}`
And here is my seach.component.html that does not work:
`
<TextField hint="Search artists" #srchstr (keyup)="searchMusic(srchstr.value)">
<Button text="Search..." (tap)="searchMusic(srchstr.value)">
<ListView [items]="searchRes" (setupItemView)="onSetupItemView($event)">
<Label [text]='ar.name'>
`
And here is what it says:
Cannot read property 'name' of undefined
OOUUTCH