2016-12-06 90 views
6

我需要读取json格式的配置文件。 json文件包含键/值对中的配置条目。我如何获得任何特定密钥的值?如何读取角度2中的配置文件条目?

我的问题是,我可以阅读整个使用http.get()或任何其他方式的json文件,但我如何得到一个特定的配置值基于一个关键?我是否需要循环/迭代项目才能获得所需的项目,还是有其他更好的方法来完成它?

的json的配置看起来像下面

{ 
    "SecurityService": "http://localhost/SecurityAPI", 
    "CacheService": "http://localhost/CacheServiceAPI" 
} 

我试图做的代码更改按照您的建议 从JSON文件

getConfiguration =(): Observable<Response> => { 
     return this.http.get('config.json').map(res => res.json()); 
    } 

读取配置数据下面的代码中调用的代码上述方法从调用组件中读取并使用配置值

this._ConfigurationService.getConfiguration() 
      .subscribe(
      (res) => { 
       this.configs = res; 
       console.log(this.configs); 
      }, 
      (error) => console.log("error : " + error), 
      () => console.log('Error in GetApplication in Login : ' + Error) 
     ); 

不过是越来越执行上面的时候,我得到了错误的

"error : SyntaxError: Unexpected token < in JSON at position 0"

是什么,我在这里做的错误,同样的代码读取JSON文件的工作在我需要阅读其他方案从JSON数据并结合电网等

我曾尝试在plunkr https://plnkr.co/edit/rq9uIxcFJUlxSebO2Ihz?p=preview

+0

你可以做'数据[“SecurityService “]'或'data.SecurityService' –

+0

你检查过JSON吗?如果你得到这个错误,这可能是一个HTML回应。这就是说数据的第一个标记是'<',这是无效的JSON。当你尝试调用'res.json()'时,会发生这种情况,调用JSON.parse –

+0

添加'http.get(..)。do(res => console.log(res.text()))'你得到。如果它是HTML,那么找出原因。 –

回答

10

重现问题“阅读”配置文件是不是在JS阅读任何其他对象不同。例如,创建一个配置变量:

export var config = { 
    title: "Hello World", 
    "SecurityService":"http://localhost/SecurityAPI", 
    "CacheService":"http://localhost/CacheServiceAPI" 
} 

,然后将其导入到你的组件使用这样的:

import { Component, Input } from '@angular/core'; 
import { config } from './config'; 

@Component({ 
    selector: 'my-app', 
    template: `{{myTitle}}<br>{{security}}<br> {{cache}}`, 
    directives: [] 
}) 
export class AppComponent { 
    myTitle = config.title; 
    security = config.SecurityService; 
    cache = config.CacheService; 

} 

完整的示例:https://plnkr.co/edit/CGtxYJkcjYt2cEzrbL00?p=preview

+1

我不想在.ts文件中的配置项。相反,它应该来自json文件。 – Krishnan

+0

@Krishnan我刚刚创建了一个例子json。你看'var config'是一个json(javascript对象)。无论你在哪里获得这个json数据,你都可以简单地使用点(config.SecurityService')或数组表示法('config [“SecurityService”]')来选择它的关键字@Pankaj也在评论 – echonax

+0

中提到错误为“error:SyntaxError:意外的标记 Krishnan