简体   繁体   English

如何在angular2 GA中使用Http提供程序?

[英]How to use Http providers in angular2 GA?

I am trying to use angular 2 Http service but I am getting 我正在尝试使用angular 2 Http服务,但我正在

Can't resolve all parameters for AppComponent: (?) 无法解析AppComponent的所有参数:(?)

Which has this signature 哪个有这个签名

 constructor(public http:Http){ }

I tracked the problem down to declaring the providers for Http. 我将问题追溯到为Http声明提供程序。

In the angular 2 quickstart they say 在角度2快速入门中,他们说

In this demo, we register providers by importing other NgModules to our root NgModule. 在此演示中,我们通过将其他NgModule导入到我们的根NgModule中来注册提供程序。

But I already have 但是我已经有

@NgModule({
    imports: [ BrowserModule, HttpModule, FormsModule ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})

So, I understand the providers should be fine. 因此,我知道提供程序应该没问题。

In the code documentation for file http.d.ts I find this: 在文件http.d.ts的代码文档中,我发现:

 * import {Http, HTTP_PROVIDERS} from '@angular/http';

But when I try to write this, I get that HTTP_PROVIDERS does not exist (I guess it is before GA) 但是当我尝试编写此代码时,我发现HTTP_PROVIDERS不存在(我想它是在GA之前)

The only way I can solve this error is by adding @Inject(Http) in the signature. 解决此错误的唯一方法是在签名中添加@Inject(Http)

How can I make it work without adding @Inject(Http) in the signature? 如何在不添加@Inject(Http)签名的情况下使其工作?

This is my systemjs config 这是我的system.js配置

  <script>
        System.config({
            transpiler: 'typescript',
            map: {
                '@angular/core': './node_modules/@angular/core/bundles/core.umd.js',
                '@angular/platform-browser-dynamic': './node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
                '@angular/platform-browser': './node_modules/@angular/platform-browser/bundles/platform-browser.umd.js',
                '@angular/compiler': './node_modules/@angular/compiler/bundles/compiler.umd.js',
                '@angular/common': './node_modules/@angular/common/bundles/common.umd.js',
                '@angular/http': './node_modules/@angular/http/bundles/http.umd.js',
                '@angular/forms': './node_modules/@angular/forms/bundles/forms.umd.js',
                'rxjs': './node_modules/rxjs'
            },
            packages: {
                './app': {
                    defaultExtension: 'ts'
                },
                '@angular/http':{
                    defaultExtension:'ts'
                },
                'rxjs': {
                    defaultExtension: 'js'
                }
            }
        })

        System.import('./app/main.ts').catch(function (err) {
            console.error(err);
        });

    </script>

This is my tsconfig.json 这是我的tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

You can see all my code at https://github.com/GuyMograbi/angular2-simple-setup 您可以在https://github.com/GuyMograbi/angular2-simple-setup看到我的所有代码

You need to add HttpModule to imports in NgModule 您需要将HttpModule添加到NgModule导入中

@NgModule({
  imports: [BrowserModule, HttpModule]
  ...
})

No need for @Inject() for Http . 不需要@Inject()用于Http

Ensure you have properly imported (TS imports) everything Http , HttpModule , ... 确保已正确导入(TS导入)所有HttpHttpModule ,...

Completely rewriting my answer to be better targeted. 完全重写我的答案以更好地针对性。

Your module: 您的模块:

import {...} from '@angular/...';

import {HttpModule} from '@angular/http';

@NgModule({
    imports: [..., HttpModule],
    declarations: [...],
    exports: [...],
    providers: [...]
})
export class AppModule {}

Your component: 您的组件:

import {Component} from '@angular/core';
import {Http} from '@angular/http';

@Component({
    selector: 'my-app',
    template: `...`
})
export class AppComponent{

    constructor(private http: Http){
    }

    private getMyData(){
        return this.http.get(...)
            .map(...)
            .subscribe(...);
    }
}

That should be all you need. 那应该是您所需要的。 There is no @Injectable decorator on the AppComponent because it's a @Component , it's not an injectable service. @Injectable上没有@Injectable装饰器,因为它是@Component ,它不是可注入服务。

Angular takes care of injecting for you, so you shouldn't need to do any kind of @Inject(Http) anywhere. Angular会为您进行注入,因此您无需在任何地方进行任何类型的@Inject(Http)

Only your own services that you create that you want components (or other services) to use should be created as @Injectable . 只有您自己创建的想要组件(或其他服务)使用的服务才应创建为@Injectable Eg 例如

import {Injectable} from '@angular/core';

@Injectable()
export class SomeService{
    doSomething(){
        //...
    }
}

You would add that SomeService to either your Module level providers array (for app-level singleton) or even your Component 's own providers array (for new instances along with the components). 您可以将该SomeService添加到Module级别的提供程序数组(用于应用程序级单例),甚至添加到Component自己的提供程序数组(用于与组件一起的新实例)。

import {SomeService} from './some.service';

@Component({
    selector: '...',
    template: '...',
    providers: [SomeService]
})
export class SomeComponent{ 
    constructor(private someService: SomeService){
        // someService is a new instance of SomeService (not a singleton)
    }
}

Notice, though, that there's no additional @Inject code - the providers (either module level or component level, depending on your needs), deal with creating an instance for you, and passing it to the constructor. 但是请注意,没有其他@Inject代码-提供程序(模块级别或组件级别,具体取决于您的需求),为您创建实例,并将其传递给构造函数。

Edit to respond to the updated question: 编辑以回答更新的问题:

I think your systemjs.config might be wrong. 我认为您的systemjs.config可能是错误的。 I see your app pointing to a ts file instead of js. 我看到您的应用指向ts文件而不是js。 Browsers don't really run ts, ts needs compiling (transpiling - pick your term of choice) into js. 浏览器并没有真正运行ts,ts需要编译(编译-选择您的选择条件)到js中。 The js is what systemjs.config should be loading, not the ts. js是systemjs.config应该加载的内容,而不是ts。

packages: {
    app: {
        main: './main.js',
        defaultExtension: 'js'
    },
    rxjs: {
        defaultExtension: 'js'
    },
    'angular-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
    }
}

You should add typescriptOptions to your systemjs configuration 您应该添加typescriptOptions您systemjs配置

index.html 的index.html

 System.config({
    transpiler: 'typescript',
    typescriptOptions: {
     "emitDecoratorMetadata": true
    },
    map: {
    ....

See also angularjs 2.0: Can't inject anything through component constructor() 另请参见angularjs 2.0:无法通过组件Constructor()注入任何东西

Your tsconfig.json isn't used in your configuration. 您的tsconfig.json未在您的配置中使用。 You're transpiling files on the fly. 您正在动态转储文件。 You could take a look at this simple seed project https://github.com/alexzuza/angular2-typescript-systemjs 您可以看一下这个简单的种子项目https://github.com/alexzuza/angular2-typescript-systemjs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM