2017-03-29 137 views
1

我正在尝试使用我的Angular2应用程序进行RESTful服务。 当我给当地的json网址(/app/config.json)时它正在工作。但是当我尝试使用下面的url时,它不起作用。angular2与宁静的服务

网址:http://localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/get

上面的网址将返回如下JSON值,

{ 
    "title": "SingerName", 
    "singer": "Singer123", 
    "id": "1", 
    "name": "Hero123" 
} 

app.module

@NgModule({ 
    declarations: [ AppComponent,HeroListComponent,HeroDetailComponent],   
    imports: [BrowserModule,HttpModule,routing], bootstrap: [AppComponent] 
}) 

HeroService.ts

getHeroes(){ 
    var headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 
    return this._http.request("localhost:8082/RESTful_Jersey_JSON/rest/‌​json/metallica/…) .map((res:Response) => res.json()); 
} 

HeroListComponent

@Component({ 
    selector: 'my-hero-detail', 
    template: ` 
     <h2>Hero List Component</h2> 
     <ul *ngFor="let hero of heroes"> 
     {{hero}} 
     <li>{{hero.id}}</li> 
     <li>{{hero.name}}</li> 
    </ul>` 
}) 
export class HeroListComponent implements OnInit { 
    heroes = []; 

    constructor(private _heroService:HeroService) {} 

    ngOnInit(){  
    this._heroService.getHeroes(). 
     .subscribe(response =>this.heroes = response);  
     }  
    } 
+1

您不能在休息请求中输入相关路径。 – echonax

+0

如果您直接在浏览器中打开它,其他链接是否有效? –

+0

是的,其他链接在浏览器/邮递员客户端中工作。 – Santhoshkumar

回答

1

如果什么返回是:

{ "title": "SingerName", "singer": "Singer123", "id": "1", "name": "Hero123" } 

这意味着这是一个对象,而不是一个数组哟你可以遍历你的模板。

所以,也许改变的变量名称只是英雄,因为它是一个对象,而不是一个数组,但是这只是一个细节;)在这里,我将使用heroes虽然:

ngOnInit(){  
    this._heroService.getHeroes(). 
    subscribe(response => this.heroes = response);  
} 

那么你不需要遍历的反应,只是显示它像这样:

<div> 
    {{heroes?.id}} 
    {{heroes?.name}} 
</div> 

,并使用安全的导航操作:)

希望这有助于它是有用的!

+0

谢谢。它正在与安全导航运营商

{{heroes?.id}} {{heroes?.name}}
合作。 – Santhoshkumar

+0

非常欢迎!是的,安全的导航运营商在异步的角度世界中是一件美妙的事情:D祝您有个愉快的夜晚和愉快的编码! :) – Alex

0

echonax说不要使用相对路径,并设置标题是这样的:

let options = new RequestOptions({ headers: headers }); 

return this._http.get("/assets/herolist.json", options).map((res:Response) => res.json()); 
+0

谢谢Bougarfaoui。 /assets/herolist.json已经在工作。我需要连接REST服务,如'http:// localhost:8082/RESTful_Jersey_JSON/rest/json/metallica/get'。 – Santhoshkumar