Açısal İSTİSNA: Http için sağlayıcı yok


333

Ben alıyorum EXCEPTION: No provider for Http!benim Açısal app. Neyi yanlış yapıyorum?

import {Http, Headers} from 'angular2/http';
import {Injectable} from 'angular2/core'


@Component({
    selector: 'greetings-ac-app2',
    providers: [],
    templateUrl: 'app/greetings-ac2.html',
    directives: [NgFor, NgModel, NgIf, FORM_DIRECTIVES],
    pipes: []
})
export class GreetingsAcApp2 {
    private str:any;

    constructor(http: Http) {

        this.str = {str:'test'};

        http.post('http://localhost:18937/account/registeruiduser/',
            JSON.stringify(this.str),
            {
                headers: new Headers({
                    'Content-Type': 'application/json'
                })
            });

3
Kayboldun HTTP_PROVIDERS.
Eric Martinez

1
ithalat / ihracat ... lütfen, herhangi biri, bu sözdizimi nedir?
vp_arth

5
Bu Dizgi Sözdizimi
daniel

10
içe / dışa aktar - JavaScript sözdizimi (ES6)
alexpods

3
Cevaplardan birinin neden içe aktarmamız gerektiğini HttpModuleve ne yaptığını açıklaması güzel olurdu .
Drazen Bjelovuk

Yanıtlar:


520

HttpModule'ü içe aktarın

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

@NgModule({
    imports: [ BrowserModule, HttpModule ],
    providers: [],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
})
export default class AppModule { }

platformBrowserDynamic().bootstrapModule(AppModule);

İdeal olarak, bu kodu iki ayrı dosyaya böldünüz. Daha fazla bilgi için:


2
Geçerli Angular2 beta sürümünde dosya çağrılır app.ts.
d135-1r43

7
Açısal cli oluşturulan projelerde dosya çağrılır main.ts.
filoxo

NgModule'm yoksa ne olur? Bir angular2 modülü geliştiriyorum ve bir NgModule yok ama testler için Http sağlayıcısına ihtiyacım var
iRaS

@Webruster yeni kontrol ettim. Hala çalışmalı. Bana kesin hata kodunu verebilir misiniz?
Philip

2
@PhilipMiglinci ... değerli cevap için teşekkürler .. açıklama için arayanlar için dosyanın app.module.ts olacağını bazı noktalar ekleyerek açıklama için bu projenin daha fazla miras kullanacak modülleri dahil etmek için temel dosya sınıflar.
shaan gola

56

> = Açısal 4.3

tanıtılan için HttpClientModule

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule, // if used
    HttpClientModule,
    JsonpModule // if used
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Açısal2> = RC.5

Kullandığınız HttpModulemodüle aktarın (burada örneğin AppModule:

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

@NgModule({
  imports: [
    BrowserModule,
    FormsModule, // if used
    HttpModule,
    JsonpModule // if used
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

İçe aktarma işlemi önceki sürümde HttpModuleeklemeye oldukça benzer HTTP_PROVIDERS.


9

14 Eylül 2016 Angular 2.0.0 sürümü ile, hala HttpModule kullanıyorsunuz. Ana cihazınız app.module.tsşöyle görünecektir:

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

@NgModule({
   bootstrap: [ AppComponent ],
   declarations: [ AppComponent ],
   imports: [
      BrowserModule,
      HttpModule,
      // ...more modules...
   ],
   providers: [
      // ...providers...
   ]
})
export class AppModule {}

Sonra sizin app.tsgibi bootstrap yapabilirsiniz:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/main/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

9

Kullanmadan önce app.module.ts dosyasındaki diziyi içe aktarmak için HttpModule öğesini ekleyin .

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

@NgModule({
  declarations: [
    AppComponent,
    CarsComponent
  ],
  imports: [
    BrowserModule,
	HttpModule  
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


9

Rc.5 beri böyle bir şey yapmak zorunda

@NgModule({
    imports: [ BrowserModule],
    providers: [ HTTP_PROVIDERS ],  
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
})
export default class AppModule { }

platformBrowserDynamic().bootstrapModule(AppModule);


5

HttpModuleApp.module.ts dosyanıza içe aktarın .

import { HttpModule } from '@angular/http';
import { YourHttpTestService } from '../services/httpTestService';

Ayrıca aşağıdaki gibi ithalat altında HttpModule beyan etmeyi unutmayın:

imports: [
    BrowserModule,
    HttpModule
  ],

4

En iyi yol, aşağıdaki gibi sağlayıcılar dizisine Http ekleyerek bileşeninizin dekoratörünü değiştirmektir.

@Component({
    selector: 'greetings-ac-app2',
    providers: [Http],
    templateUrl: 'app/greetings-ac2.html',
    directives: [NgFor, NgModel, NgIf, FORM_DIRECTIVES],
    pipes: []
})

Kim onu ​​yanlış işaretledi, sebebinin ne olduğunu öğrenebilir miyim?
Shivang Gupta

5
Ben aşağı itmedim, ama nedeni muhtemelen Httpher bileşen için yeni bir nesne istemiyorum . NgModuleDüzeyinde içe aktarılarak gerçekleştirilen uygulama için tek bir tane olması daha iyidir .
Ted Hopp

3

RC5'ten itibaren HttpModule'ü şu şekilde içe aktarmanız gerekir:

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

daha sonra HttpModule'u yukarıda Günter tarafından belirtildiği gibi içe aktarma dizisine dahil edin.


3

Sadece aşağıdaki kütüphaneleri ekleyin:

import { HttpModule } from '@angular/http';
import { YourHttpTestService } from '../services/httpTestService';

ve http sınıfını providersaşağıdaki gibi ekleyin :

@Component({
  selector: '...',
  templateUrl: './test.html',
  providers: [YourHttpTestService]

3

Testlerinizde bu hata varsa, tüm hizmetler için Sahte Hizmet oluşturmanız gerekir:

Örneğin:

import { YourService1 } from '@services/your1.service';
import { YourService2 } from '@services/your2.service';

class FakeYour1Service {
 public getSomeData():any { return null; }
}

class FakeYour2Service {
  public getSomeData():any { return null; }
}

Ve her şeyden önce

beforeEach(async(() => {
  TestBed.configureTestingModule({
    providers: [
      Your1Service,
      Your2Service,
      { provide: Your1Service, useClass: FakeYour1Service },
      { provide: Your2Service, useClass: FakeYour2Service }
    ]
  }).compileComponents();  // compile template and css
}));

3
**

Basit ruh: HttpModule ve HttpClientModule'u app.module.ts dosyasına aktarın

**

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



@NgModule({
 declarations: [
   AppComponent, videoComponent, tagDirective, 
 ],
 imports: [
  BrowserModule, routing, HttpClientModule, HttpModule

],
providers: [ApiServices],
bootstrap: [AppComponent]
})
export class AppModule { }

Bu çözüm çalışır, ancak HttpModule Açısal 5.2'de kullanımdan kaldırılmış olarak işaretlenir. Bazı bileşenlerin yükseltilmediğini ve hala eski Http uygulamasını kullandığını düşünüyorum.
Sobvan

1

Yapmanız gereken tek şey, aşağıdaki app kütüphanelerini tour app.module.ts dosyasına dahil etmek ve onu içe aktarmalarınıza dahil etmektir:

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

@NgModule({
  imports:    [ HttpModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

1

Kodumda bu sorunla karşılaştım. Bu kodu yalnızca app.module.ts dosyasına koydum.

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

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

1
Lütfen mevcut cevapları tekrarlamayın. Bunu yapmak topluluğa değer katmaz.
isherwood

1

import { HttpModule } from '@angular/http'; module.ts dosyasına paketleyin ve içe aktarmalarınıza ekleyin.


1

Sadece ikisini de app.module.ts dosyasına ekliyorum:

"import { HttpClientModule }    from '@angular/common/http'; 

&

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

Şimdi iyi çalışıyor .... Ve eklemeyi unutmayın

@NgModule => Imports:[] array

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.