【问题标题】:why my angular 2 service in not visible to my app?为什么我的 Angular 2 服务对我的应用程序不可见?
【发布时间】:2016-02-04 08:22:59
【问题描述】:

我正在尝试通过我的 Angular 服务读取 JSON 文件。 当我不使用该服务时,我可以轻松读取 JSON 数据并将其绑定到变量中。 但是当我使用服务来执行此操作时,它不起作用。 它显示以下错误:

Failed to load resource: the server responded with a status of 404.

我确定我写的路径是正确的。

目录结构

下面是代码:

  1. app.component.ts

import {Component} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import { DataService } from '../services/data.service';

@Component({
    selector: 'my-app',
    providers: [DataService],
    templateUrl: 'app/app.component.html'
})
export class AppComponent {
    public record;
    constructor(private dataService: DataService) { }
    ngOnInit() {
        this.dataService.getDetails()
        .subscribe((customers:any[]) => {
          this.record = customers;
        });              
    }  
}
  1. data.service.ts

import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class DataService {    
    constructor(private http: Http) { }    
    getDetails() {
        return this.http.get('../uicomponent.json')
            .map((res:Response) => res.json());     
    }
}
  1. 引导配置

<script>
      System.config({
        map: { 'rxjs': 'node_modules/rxjs' },
        packages: {
          app: { format: 'register', defaultExtension: 'js' },
          'rxjs': {defaultExtension: 'js'}
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
  1. main.ts

import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/add/operator/map';
import {AppComponent} from './app.component'
 
bootstrap(AppComponent, [
  HTTP_PROVIDERS
]);

【问题讨论】:

  • 我不确定我是否理解您的问题。您是否认为 Angular 没有找到该服务(如问题标题所示)或者该服务无法获取 json 文件?请求的 URL 是什么?实际应该是怎样的?
  • angular 2 无法找到服务..虽然我写的路径正确..因为我在其他项目中以同样的方式使用过服务,它们工作正常@GünterZöchbauer
  • 您的路径似乎有效。您能否分享更多信息,例如 SystemJS 或 Webpack 配置,可能是您的存储库或 plunker...?
  • 您能提供完整的错误信息吗?我的意思是哪个资源加载失败...谢谢!
  • 我猜问题可能来自你的相对路径 ('../uicomponent.json')...

标签: javascript angularjs json angular


【解决方案1】:

services 文件夹应位于 app 文件夹下。根据您的 SystemJS 配置,使用此配置仅加载此文件夹下的资源:

System.config({
  (...),
  packages: {
    app: { format: 'register', defaultExtension: 'js' },
    (...)
  }
});
format: 'register', defaultExtension: 'js'

这意味着 SystemJS 将自动尝试使用 js 扩展名加载模块。

所以结构应该如下:

project
  - app
    - app.component.ts
    - main.ts
    - services
      - data.service.ts

app.component.ts 文件中,您可以使用以下命令导入服务:

import {DataService} from './services/data.service';

根据其配置,如果 TypeScript 编译器之前完成了它的工作,SystemJS 将尝试加载应该存在的localhost:3000/app/services/data.service.js ;-)

蒂埃里

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多