#include <stdio.h>
int main(int argc, char **argv)
{
size_t i;
size_t filename_i = -1;
for (i = 0; i < argc; i++)
{
char const *option = argv[i];
if (option[0] == '-')
{
printf("I am a flagged option");
switch (option[1])
{
case 'a':
/*someting*/
break;
case 'b':
break;
case '-':
/* "--" -- the next argument will be a file.*/
filename_i = i;
i = i + 1;
break;
default:
printf("flag not recognised %s", option);
break;
}
}
else
{
printf("I am a positional argument");
}
/* At this point, if -- was specified, then filename_i contains the index
into argv that contains the filename. If -- was not specified, then filename_i will be -1*/
}
return 0;
}
Вот часть моего кода, который анализирует JSON, это может быть полезно для вас:
import { Component, Input } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class AppServices{
constructor(private http: Http) {
var obj;
this.getJSON().subscribe(data => obj=data, error => console.log(error));
}
public getJSON(): Observable<any> {
return this.http.get("./file.json")
.map((res:any) => res.json())
.catch((error:any) => console.log(error));
}
}
Я думаю, что папка с ресурсами общедоступна, вы можете получить к ней доступ непосредственно в браузере
http: // localhost: 4020 / assets /
в отличие от других приватных папок, отбросьте свой json-файл в папку с ресурсами
В Angular 5
вы можете просто сказать
this.http.get<Example>('assets/example.json')
Это даст вам Observable<Example>
Мне нужно было загрузить файл настроек синхронно, и это было моим решением:
export function InitConfig(config: AppConfig) { return () => config.load(); }
import { Injectable } from '@angular/core';
@Injectable()
export class AppConfig {
Settings: ISettings;
constructor() { }
load() {
return new Promise((resolve) => {
this.Settings = this.httpGet('assets/clientsettings.json');
resolve(true);
});
}
httpGet(theUrl): ISettings {
const xmlHttp = new XMLHttpRequest();
xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return JSON.parse(xmlHttp.responseText);
}
}
Затем он предоставляется как app_initializer, который загружается до остальной части приложения.
app.module.ts
{
provide: APP_INITIALIZER,
useFactory: InitConfig,
deps: [AppConfig],
multi: true
},
Храните файл json в каталоге Assets (parallel to app dir)
. Обратите внимание, что если бы вы сгенерировали с новым новым именем YourAppname - этот каталог ресурсов существует в той же строке с каталогом «app», а службы должны быть дочерним каталогом каталога приложений. Может выглядеть так:
:: app / services / myservice.ts
getOrderSummary(): Observable {
// get users from api
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Вам нужно сделать HTTP звонок для вашего games.json
, чтобы получить его. Что-то вроде:
this.http.get(./app/resources/games.json).map
service.service.ts
--------------------------------------------------------------
import { Injectable } from '@angular/core';
import { Http,Response} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable({
providedIn: 'root'
})
export class ServiceService {
private url="some URL";
constructor(private http:Http) { }
//getData() is a method to fetch the data from web api or json file
getData(){
getData(){
return this.http.get(this.url)
.map((response:Response)=>response.json())
}
}
}
display.component.ts
--------------------------------------------
// В этом компоненте получить данные с помощью subscribe () и сохранить их в локальном объекте как dataObject и отобразить данные в display.component.html, например {{dataObject .property Name}}.
import { Component, OnInit } from '@angular/core';
import { ServiceService } from 'src/app/service.service';
@Component({
selector: 'app-display',
templateUrl: './display.component.html',
styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
dataObject :any={};
constructor(private service:ServiceService) { }
ngOnInit() {
this.service.getData()
.subscribe(resData=>this.dataObject =resData)
}
}
Если вы используете angular-cli Храните файл json в папке «Активы» (параллельно с каталогом app dir)
return this.http.get('<json file path inside assets folder>.json'))
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Примечание: здесь вам нужно только указать путь в папке с ресурсами, например assets / json / oldjson.json, тогда вам нужно написать путь, как /json/oldjson.json
Если вы используете webpack, тогда вам нужно следовать над той же структурой внутри общей папки как аналогичная папка с ресурсами.
res.text()
вместоres.json()
во время.map
– Pardeep Jain 17 July 2017 в 10:22console.log
возвращаетundefined
, а также регистрирует ошибку. Это было полезно в моем случае. @Pardeep, как я сказал, это решение для моего дела, но ваш вклад может помочь другим людям. Благодарю. – Bünyamin Sarıgül 17 July 2017 в 10:50assets/file.json
, это может сработать. Если вы отправляете отдельный вопрос, я могу показать конфигурацию angular-cli для использования файлов из другого файла. – Bünyamin Sarıgül 31 May 2018 в 07:07