I'm new to nativescript angular2. So far I followed documentation and did static datas with listview.
I placed my json file in app/utils/countries.json
.
I don't know how to get the local file path to parse the json.Need suggestion regarding this.
Below I have posted the codes for listview with static data.
typescript:
import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";
@Component({
selector: "ns-app",
templateUrl: "app.component.html",
})
export class AppComponent implements OnInit {
arrList: Array<Object> = [];
ngOnInit() {
this.arrList.push({ name: "India" });
this.arrList.push({ name: "Sri Lanka" });
}
}
HTML:
<page-router-outlet></page-router-outlet>
<GridLayout>
<ListView [items]="arrList" class="small-spacing">
<ng-template let-item="item">
<Label [text]="item.name" class="medium-spacing"></Label>
</ng-template>
</ListView>
</GridLayout>
countries.json: (app/utils/countries.json):
{
"countries": [
{"id":1,"name":"india"},
{"id":2,"name":"Sri Lanka"}
]
}
Below codes worked for me to retrieve the local path json objects and shown it to command prompt.
getdata.component.ts
import {Injectable} from "@angular/core";
import {Http,Response} from '@angular/http';
import { HttpModule } from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/startWith';
import 'rxjs/Rx';
@Injectable()
export class GetData {
constructor(private _http:Http) {
}
getObjectData() {
return this._http.get('/utils/countries.json')
.map(data => console.log("Test", JSON.stringify(data.json())));
}
}
app.component.ts:
import { Component, OnInit, ViewChild } from "@angular/core";
import { GetData } from './pages/getData.component';
import { Observable } from 'rxjs/Observable';
import {Http,Response, RequestOptions} from '@angular/http';
@Component({
selector: "ns-app",
templateUrl: "app.component.html",
styleUrls: ["./app.css"],
providers: [GetData]
})
export class AppComponent implements OnInit {
setData : string;
objectData : any;
constructor(public getData: GetData, private http: Http) {
}
ngOnInit() {
console.log("first", "Test");
this.getData.getJsonObject()
.subscribe(data => this.getData = JSON.stringify(data),
error => alert(error),
() => console.log("finished")
);
}
}