简体   繁体   English

没有在注入错误和没有提供者错误时提供服务的提供者

[英]No provider for service at Injection Error and at No provider error

error message I am the new man to angular 2. I am getting No provider for service at injection error and no provider error even i specified the provider in the app module. 错误消息我是angular 2的新手。我得到了注射时没有提供服务的提供程序错误,即使我在应用程序模块中指定了提供程序,也没有提供程序错误。 The code is cribs.service.ts 代码是cribs.service.ts

import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class CribsService {

    constructor(private http: Http) { }


      getAllCribs()
        {
         return this.http.get('data/Cribs.json').map(res => res.json());
         }

   }

app.module.ts app.module.ts

enter code here
import { AppComponent } from './app.component';
import { CribsListingComponent } from './cribs-listing/cribs-
 listing.component';

 import { CribCardComponent } from './crib-card/crib-card.component';
 import {HttpModule} from '@angular/http';
 import {CribsService} from './service/cribs.service';

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

My file heirarachy is : c:/User/Desktop/projectname/src/app/service/crib.service.ts c:/User/Desktop/projectname/src/app/app.module.ts 我的文件传承是:c:/User/Desktop/projectname/src/app/service/crib.service.ts c:/User/Desktop/projectname/src/app/app.app.module.ts

app.component.ts app.component.ts

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


@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],

 })
export class AppComponent {
 title = 'app works';  
 }

cribs-listing.component.ts 婴儿床,listing.component.ts

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import {CribsService} from './../service/cribs.service';
import 'rxjs/add/operator/map';

  @Component({
  selector: 'app-cribs-listing',
  templateUrl: './cribs-listing.component.html',
  styleUrls: ['./cribs-listing.component.css']  
   })

export class CribsListingComponent implements OnInit {

Cribs: Array<any>;
error:String;

constructor(private http:Http,
private cribsservice: CribsService  
) { }

ngOnInit() {

this.cribsservice.getAllCribs()
.subscribe( 
  data => this.Cribs= data,
  error => this.error=error.statusText
);


 }

}

try giving the provider service name at the component level like belo 尝试在组件级别(例如belo)中提供提供商服务名称

@Component({
    selector: 'my-compoment',
    template: '<h1>{{ title }}</h1>',
    providers: [CribsService]
})

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

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