【问题标题】:angular2 with restful serviceangular2 提供宁静的服务
【发布时间】:2017-03-29 11:50:20
【问题描述】:

我正在使用我的 Angular2 应用程序尝试 RESTful 服务。 当我提供本地 json url (/app/config.json) 时,它正在工作。但是当我尝试使用以下网址时它不起作用。

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

上面的url会返回如下的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);    
      }    
  }

【问题讨论】:

  • 你不能在休息请求中输入这样的相对路径。
  • 如果直接在浏览器中打开,其余链接是否有效?
  • 是的,其余链接在浏览器/邮递员客户端中工作。
  • 谢谢@echonax。我可以使用这样的请求方法调用该 url。_http.request 吗?
  • @Santhoshkumar 好的,但是你在哪里/如何使用getHeroes?请编辑您的问题并将其添加到此处,从评论部分很难阅读。

标签: web-services angular angular2-services restful-url


【解决方案1】:

如果返回的是:

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

这意味着这是一个对象,而不是您可以在模板中迭代的数组。

所以也许将变量名改为 hero,因为它是一个对象而不是一个数组,但这只是一个细节;)这里我将使用 heroes

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

那么你就不需要迭代响应了,直接显示就可以了:

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

使用安全导航操作符很有用:)

希望这会有所帮助!

【讨论】:

  • 谢谢。它与安全导航运算符
    {{heroes?.id}} {{heroes?.name}}
    一起使用。
  • 不客气!是的,安全导航操作员在 angular 的异步世界中是一件很棒的事情:D 祝你晚上/晚上愉快,编码愉快! :)
【解决方案2】:

正如echonax 所说,不要使用相对路径并像这样设置标题:

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多