簡體   English   中英

angualr2使用http.get()請求本地json數據

[英]angualr2 use the http.get() to request the local json data

最近我正在學習angular2的http客戶端,並且已經用angular-in-memory-web-api完成了演示。現在我想使用http.get請求本地json數據,但是瀏覽器告訴我zone.js:1980 GET http://localhost:4200/app/hero.json 404 (Not Found) ,在閱讀有關URLAngular2 404的相關文章后:http:// localhost / WebApi2 / api / hero與之 類似的angular get ,我從我的項目中刪除了'angular-in-memory-web-api' InMemoryWebApiModule.forRoot(HeroData) 'angular-in-memory-web-api'InMemoryWebApiModule.forRoot(HeroData)和相關文件,但是仍然存在404 (Not Found)的問題,關鍵代碼如下:

//app.module.ts
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    JsonpModule,
  ],
  declarations: [
    AppComponent,
    HeroListComponent,
    HeroListPromiseComponent,
    WikiComponent,
    WikiSmartComponent
  ],
  providers: [ requestOptionsProvider ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

//hero.service.ts enter code here

@Injectable()
export class HeroService {
  private heroesUrl = 'app/hero.json';

  constructor (private http: Http) {}

  getHeroes(): Observable<Hero[]> {
    // debugger;
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }
  private extractData(res: Response) {
    // http.get or http.post return the json obj
    let body = res.json();
    return body.data || { };
  }

如果您需要所有代碼,我已將其推送到我的github。這是地址

任何人都可以幫助我

您需要更改webpack配置。 嘗試這個:

{
                test: /\.json$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].json'
                        }
                    }
                ]
            }

如果您使用vendor.ts文件,請嘗試以下操作:

import './app/hero.json';

服務中:

@Injectable()
export class HeroService {
  private heroesUrl = './app/hero.json';

  constructor (private http: Http) {}

  getHeroes(): Observable<Hero[]> {
    // debugger;
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }
  private extractData(res: Response) {
    // http.get or http.post return the json obj
    let body = res.json();
    return body.data || { };
  }

感謝所有嘗試幫助我解決問題的人。就在此時,我找到了答案,這意味着我們應該將可訪問資源放在資產文件中,以便用戶可以從服務器獲取。因此,我嘗試一下,問題是解決了。 希望這對遇到問題的每個人都有幫助; 我看到的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM