Angular2 HttpClient 使用 Rest API

Angular2 HttpClient to consume Rest API

使用Angular2,我开发了教程(The Hero Editor)中给出的示例。

https://angular.io/tutorial/toh-pt6

默认情况下,它使用可通过同一示例中创建的 Http 客户端访问的数据调用 self-in-memory-store。

所有这些运行在localhost:3000(默认给定的端口)中完美。

现在我在 Java 中开发了一个休息 api 服务器,它 运行 在 localhost:8080 中使用本教程非常完美:

http://spring.io/guides/gs/rest-service/

然而,当我切换 URL 时,Angular 服务必须从中获取数据,我收到以下错误:

ERROR Error: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost:8080/heroes
at resolvePromise (zone.js:769)
at resolvePromise (zone.js:740)
at zone.js:817
at ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (ng_zone.ts:253)
at ZoneDelegate.invokeTask (zone.js:423)
at Zone.runTask (zone.js:191)
at drainMicroTaskQueue (zone.js:584)
at XMLHttpRequest.ZoneTask.invoke (zone.js:490)

完成 http 响应:

但我检查了 url,它运行良好。

我还需要告诉服务部任何其他信息吗? 这是所有应该完成的地方。

//private heroesUrl = 'api/heroes'; // Old URL (to get the own data storage)
private heroesUrl = `http://localhost:8080/heroes`; // New URL to get the data from working local Rest API running in other port.

constructor (private http: Http) { }

getHeroes(): Promise<Hero[]> {
    //return Promise.resolve(HEROES);
    return this.http.get(this.heroesUrl)
      .toPromise()
      .then(response => response.json().data as Hero[])
      .catch(this.handleError)
} // stub

编辑:回答评论,我在下面显示应用程序模块代码。顺便说一句,它是我在问题开头链接的英雄编辑器 Angular 教程中的 app.module.ts 的精确副本。

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';

import { AppRoutingModule }     from './app-routing.module';

// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data.service';

import { AppComponent }  from './app.component';
import { DashboardComponent} from './dashboard.component'
import { HeroDetailComponent } from './hero-detail.component';
import { HeroSearchComponent } from './hero-search.component';
import { HeroesComponent } from './heroes.component';
import { HeroService }     from './hero.service';


@NgModule({
  imports:      [
    BrowserModule,
    FormsModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),
    AppRoutingModule
   ],
  declarations: [
    AppComponent,
    HeroDetailComponent,
    HeroesComponent,
    DashboardComponent,
    HeroSearchComponent
  ],
  providers: [ HeroService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

有人知道吗?我看到了一些例子,他们向 headers 添加了更多信息。那有必要吗?有任何安全问题吗?

我找到了解决方案。

@AJT_82给了我主要线索。

如应用模块 (app.module.js) 文件中所述,我的应用正在从 InMemory 存储系统中获取数据。

当我评论这一行时:

//InMemoryWebApiModule.forRoot(InMemoryDataService)

它刚刚开始从 URL 获取数据提供给 localhost:8080/heroes Rest API。

抱歉让您浪费了时间。