如何在组件内部使用服务方法? [英] How to use service method inside a component?

查看:49
本文介绍了如何在组件内部使用服务方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在组件内部使用服务方法.我有一个服务和一个组件.

I am not able to use the service method inside a component. I have a service and a component.

组件

import { Component, OnInit } from '@angular/core';
import { Customer, Userdetails} from "./usermaster.model";
import { UsermasterService } from './usermaster.service';

@Component({
  selector: 'ngx-usermaster',
  templateUrl: './usermaster.component.html',
  styleUrls: ['./usermaster.component.scss'],
  providers:  [ UsermasterService ]
})
export class UsermasterComponent implements OnInit {
  values: any;
  UsermasterService: any;
  constructor(private service: UsermasterService) { }
  cust:Customer;
  user_details:Userdetails;
  ngOnInit() {
   this.cust={id:1,name:'dinesh'};
   console.log(this.cust);
   this.values = this.UsermasterService.get_data();
   console.log(this.values);
  }
 }

服务:

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

@Injectable({
  providedIn: 'root'
})
export class UsermasterService {
  httpClient: any;

  constructor() { }

  get_data(){
    var array=[];
    array['id']='1';
    array['name']='dineshss';
    return array;
//     this.httpClient.get('http://localhost/tasker/api/index.php/Welcome/get_data')
// .subscribe(
//   (data:any[])=>{
//     console.log(data);
//   }
// )
  }

}

我需要在component.ts中调用方法get_data,当我运行代码时,我得到的错误无法读取未定义的属性get_data.请帮我解决这个问题.

I need to call the method get_data in component.ts When i run a code i get the error cannot read property get_data of undefined. Please help me fix this.

推荐答案

由于在 UsermasterComponent 中, this.UsermasterService 是未定义的.您将其声明为属性,但从不为其分配任何值.属性 UsermasterService 和类 UsermasterService 之间没有任何连接.

Because in UsermasterComponent, this.UsermasterService is undefined. You declare it as a property, but never assign it any value. There's no connection whatsoever between the property UsermasterService and the class UsermasterService.

使用构造函数

  constructor(private service: UsermasterService) { }

您应该以 this.service 身份访问服务.

you should access the service as this.service.

这篇关于如何在组件内部使用服务方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆