无法在Angular 5中获取本地json文件-持久性404错误

时间:2019-02-20 16:17:19

标签: json angular typescript rxjs angular-httpclient

我已经阅读了所有其他有关此问题的文章或帖子。我一生都无法找出这个简单任务在哪里出问题。 (特别是紧跟this example之后。)我一定在做一些明显很愚蠢的事情,但是我一直在看这个东西,以至于看不到它。

我在assets / mockData中有一个名为isRecognized.json的json文件。我已经将模拟数据目录添加到我的webpack配置文件中,因此它包含在/ dist目录中。如果我转到http:localhost:4200 / assets / mockData / isRecognized.json,我就能看到该文件,因此我知道它可用。

但是,当我尝试使用HTTP Client检索文件时,无论我尝试什么,它都会抛出404。

编辑:我使用的是Webpack,而不是Angular CLI。

app.component.ts

import { MyService } from './services/my.service';
import { Component, OnInit, Renderer2 } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

/*
* Main app component that houses all views.
*/
@Component({
    selector: 'app-comp',
    templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {

    constructor(
        private route: ActivatedRoute, private service: MyService
    ) {}

    ngOnInit() {
      this.service.isRecognized();
    }

}

my.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class MyService {

  constructor(private http: HttpClient) { }

  isRecognized() {
    this.getJSON('isRecognized').subscribe(data => {
      console.log(data);
    });
  }

  getJSON(fileName): Observable<any> {
    return this.http.get('http://localhost:4200/assets/mockData/' + fileName + '.json');
  }
}

我在浏览器控制台中看到的错误是:

AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: [object Object]
    at viewWrappedDebugError (core.js:9795)
    at callWithDebugContext (core.js:15101)
    at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:14628)
    at ViewRef_.webpackJsonp../node_modules/@angular/core/esm5/core.js.ViewRef_.detectChanges (core.js:11605)
    at core.js:5913
    at Array.forEach (<anonymous>)
    at ApplicationRef.webpackJsonp../node_modules/@angular/core/esm5/core.js.ApplicationRef.tick (core.js:5913)
    at core.js:5746
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
    at Object.onInvoke (core.js:4756)

如果我调试错误,则可以看到错误的主体是: enter image description here

4 个答案:

答案 0 :(得分:2)

仅使用以下网址,我就可以在我的应用程序中成功完成此工作:

private productUrl = 'api/products/products.json';

请注意,它不包含路径的localhost部分。

因此,请尝试以下类似操作:

'assets/mockData/' + fileName + '.json'

还要确保您的angular.json的路径在资产下列出:

        "assets": [
          "src/favicon.ico",
          "src/assets",
          "src/api"
        ],

注意:我也没有做任何 修改我的webpack配置。 (但是我正在使用CLI。)

如果您想查看一些访问json文件的工作代码,这里有一个示例:

https://stackblitz.com/edit/github-gettingstarted-deborahk

答案 1 :(得分:0)

我建议订阅该组件,然后从服务中返回一个Observable:

服务:

@Injectable()
export class MyService {

  constructor(private http: HttpClient) { }

  isRecognized(fileName): Observable<any> {
    return this.http.get('http://localhost:4200/assets/mockData/' + fileName + '.json');
  }

}

组件:

export class AppComponent implements OnInit {

    constructor(
        private route: ActivatedRoute, private service: MyService
    ) {}

    ngOnInit() {
      this.service.isRecognized(fileName)
         .subscribe(data => {
              console.log(data);
         });
    }
}

答案 2 :(得分:0)

虽然这可能不是直接解决特定问题的方法,但是您应该查看npm软件包json-server。在开发和测试客户端时,我用它来模拟API。

json-server npm

它将在端口3000上运行节点Web服务器,并且非常易于使用。

请参阅此教程示例,了解如何使用它: Mock api with json-server

可能有更好的示例,并且没有必要设置代理,但应该足够好。

答案 3 :(得分:0)

终于找到答案了!我在app.module.ts文件中将其导入:

InMemoryWebApiModule.forRoot(InMemoryDataService, { dataEncapsulation: false })

删除此错误将立即解决此问题。