简体   繁体   English

每当我尝试从服务中调用方法时,服务的状态都未定义

[英]Service s undefined whenever I try to call a method from it

I'm following Jogesh Muppala's Angular course on Coursera, and I'm stuck at the beginning of Week 4, where he's using HttpClient to communicate with the server. 我正在按照Jogesh Muppala在Coursera上进行的Angular课程学习,而我被困在第4周的开始,在那里他使用HttpClient与服务器进行通信。

I've followed the instructions exactly, but his instructions seem to break my program. 我完全按照指示进行操作,但是他的指示似乎破坏了我的程序。 DishServices is a service that retrieves data from the server, and is injected into one of the components, which calls on the service to do the retrieval. DishServices是一种从服务器检索数据的服务,并注入到其中一个组件中,后者调用该服务进行检索。 However, whenever that call is made, I get nothing on the page and this in the console. 但是,无论何时打电话,我在页面上什么都没有,在控制台中什么也没有。

MenuComponent_Host.ngfactory.js? MenuComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'getDishes' of undefined at MenuComponent.push../src/app/menu/menu.component.ts.MenuComponent.ngOnInit (menu.component.ts:18) at checkAndUpdateDirectiveInline (core.js:9250) at checkAndUpdateNodeInline (core.js:10514) at checkAndUpdateNode (core.js:10476) at debugCheckAndUpdateNode (core.js:11109) at debugCheckDirectivesFn (core.js:11069) at Object.eval [as updateDirectives] (MenuComponent_Host.ngfactory.js? [sm]:1) at Object.debugUpdateDirectives [as updateDirectives] (core.js:11061) at checkAndUpdateView (core.js:10458) at callViewAction (core.js:10699) [sm]:1错误TypeError:无法在checkAndUpdateDirectiveInline(在MenuComponent.push ../ src / app / menu / menu.component.ts.MenuComponent.ngOnInit(menu.component.ts:18)处读取未定义的属性“ getDishes”分别在checkAndUpdateNodeInline(core.js:1014)在checkAndUpdateNode(core.js:10476)在debugCheckAndUpdateNode(core.js:11109)在debugCheckDirectivesFn(core.js:11069)在Object.eval [作为updateDirectives] (MenuComponent_Host.ngfactory.js?[sm]:1)在callViewAction(core.js:10699)在checkAndUpdateView(core.js:10458)在Object.debugUpdateDirectives [作为updateDirectives](core.js:11061)

As it happens, I prefer to use the older style of writing providers, and it revealed an error there. 碰巧的是,我更喜欢使用较旧的编写提供程序样式,这显示了那里的错误。

  providers: [{provide: DishService,                useValue: new DishService()},
          {provide: PromotionService,           useValue: new PromotionService()},
          {provide: ProcessHTTPMessageService,  useValue: new ProcessHTTPMessageService()},
          {provide: 'BaseURL',                  useValue: baseURL}
        ],

There's an error at DishService(), saying that it has the wrong number of arguments. DishService()发生错误,表示参数数量错误。 When I check DishService, 当我检查DishService时,

   import {Dish} from '../shared/dish';
   import {DISHES } from '../shared/dishes';
   import {Observable, of} from 'rxjs';
   import { delay } from 'rxjs/operators';

   import { map } from 'rxjs/operators';
   import { HttpClient } from '@angular/common/http';
   import { baseURL } from '../shared/baseurl';
   import { Injectable } from '@angular/core';


   export class DishService {

  constructor(private http: HttpClient) {

   }

  getDishes(): Observable<Dish[]>{
    return this.http.get<Dish[]>(baseURL + 'dishes');

  }

}

There's the HttpClient in the constructor, which implies that it needs an object like that to be instantiated. 构造函数中有HttpClient,这意味着它需要实例化这样的对象。 The tutorial does not specify to to provide a new HttpClient in the providers. 本教程未指定在提供程序中提供新的HttpClient。 I have tried switching to the new style of writing providers, with Injectable providedIn root, with no success. 我尝试使用root可提供Injectable提供的方式切换到新的编写提供程序样式,但没有成功。

EDIT: Code from MenuComponent 编辑:来自MenuComponent的代码

import { Component, OnInit, Inject } from '@angular/core';
import { Dish } from '../shared/dish';
import {DishService} from '../services/dish.service';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {

    dishes: Dish[];

  constructor(private dishService: DishService, @Inject('BaseURL') private BaseURL) { }

  ngOnInit() {
    console.log("fkvjndf");
     this.dishService.getDishes().subscribe(dishes => this.dishes = dishes);
  }


}

EDIT: 编辑:

Replaced 更换

  providers: [{provide: DishService,                useValue: new DishService()},
          {provide: PromotionService,           useValue: new PromotionService()},
          {provide: ProcessHTTPMessageService,  useValue: new ProcessHTTPMessageService()},
          {provide: 'BaseURL',                  useValue: baseURL}
        ],  

With

  providers: [{provide: DishService},
          {provide: PromotionService},
          {provide: ProcessHTTPMessageService},
          {provide: 'BaseURL', useValue: baseURL}
        ],  

and added 并添加

@Injectable({
  providedIn: 'root'
})

to DishService.ts 到DishService.ts

only to get the same error message 只得到相同的错误信息

MenuComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'getDishes' of undefined at MenuComponent.push../src/app/menu/menu.component.ts.MenuComponent.ngOnInit (menu.component.ts:18) at checkAndUpdateDirectiveInline (core.js:9250) at checkAndUpdateNodeInline (core.js:10514) at checkAndUpdateNode (core.js:10476) at debugCheckAndUpdateNode (core.js:11109) at debugCheckDirectivesFn (core.js:11069) at Object.eval [as updateDirectives] (MenuComponent_Host.ngfactory.js? [sm]:1) at Object.debugUpdateDirectives [as updateDirectives] (core.js:11061) at checkAndUpdateView (core.js:10458) at callViewAction (core.js:10699)

The problem is that you have defined a parameter in the constructor, but when you call new DishService() you don't pass this value in. In general, you can simplify your providers section and should be able to fix your problem in the same turn. 问题是您已经在构造函数中定义了一个参数,但是当您调用new DishService()您不会传递该值。通常,您可以简化providers部分,并且应该能够以相同的方式解决问题。转。

providers: [
    DishService,
    PromotionService,,
    ProcessHTTPMessageService,
    {provide: 'BaseURL', useValue: baseURL}
],

If you don't need any special construction for your provider, you can just pass in the class and the dependency injection framework will take care of the dependencies for you. 如果您的提供程序不需要任何特殊的构造,则只需传入类,然后依赖项注入框架将为您处理依赖项。

I don't see why you should use the older style of writing providers , but if you want to make it more complicated you need to use a factory, once you require dependencies. 我不明白为什么您应该使用the older style of writing providers ,但是如果要使其变得更复杂,则需要依赖项后就需要使用工厂。 But as I see it there is no point in doing that in your case. 但是据我所知,在您的情况下这样做毫无意义。

I think you need to add @Injectable() decorator in your service class and also these after this code.. 我认为您需要在服务类中以及在此代码之后添加@Injectable()装饰器。

   import {Dish} from '../shared/dish';
   import {DISHES } from '../shared/dishes';
   import {Observable, of} from 'rxjs';
   import { delay } from 'rxjs/operators';

   import { map } from 'rxjs/operators';
   import { HttpClient } from '@angular/common/http';
   import { baseURL } from '../shared/baseurl';
   import { Injectable } from '@angular/core';

   @Injectable({
     providedIn: 'root',
   })
   export class DishService {

  constructor(private http: HttpClient) {

   }

  getDishes(): Observable<Dish[]>{
    return this.http.get<Dish[]>(baseURL + 'dishes');

  }

}

No need to place this service in provider options of NgModule decorator of root module (like : app.module) due to the 'providedIn' flag and must need to add HttpClientModule in imports options of NgModule decorator also. 由于提供了'providedIn'标志,因此无需将此服务放置在根模块的NgModule装饰器的提供程序选项中(例如:app.module),并且还必须在NgModule装饰器的导入选项中添加HttpClientModule。 Hope this helps. 希望这可以帮助。

暂无
暂无

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

相关问题 每当我尝试从 UserData 获取值时,ThreeJS 返回 undefined - ThreeJS returning undefined whenever I try to get a value from UserData 每当我调用保存方法时调用保存方法 - Calling saving method whenever I call save method 从Cordova插件的服务调用javascript方法 - Call javascript method from Cordova Plugin's service 每当我尝试访问 record.username 时,我都会收到“TypeError: Cannot read property 'username' of undefined” - I am getting "TypeError: Cannot read property 'username' of undefined" whenever I try to access record.username Mongoose 无法将“”的属性设置为未定义,每当我尝试创建新条目时。即使模式被声明为正确 - Mongoose cannot set property of “ ” to undefined,Whenever i try to create a new entry.Eventhough the schema is declared right TypeError:无法调用未定义的方法“ closeFileCSV”-尝试/最终阻止 - TypeError: Cannot call method “closeFileCSV” of undefined — try/finally block 当我尝试从applet调用方法时,出现“对象不支持此属性或方法” - “Object doesn't support this property or method” occurs, when I try to call method from applet 从服务调用方法到控制器 - Call a method from a service into a controller javascript,每当我尝试计算参数的平均值时,当它为假时返回真 - javascript, returning true when it's false whenever I would try to calculate the average of parameters AngularJs从控制器调用服务功能未定义 - AngularJs call service function from controller undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM