如何在组件内部使用服务方法?

时间:2019-04-14 17:27:51

标签: angular service components

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

组件

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。请帮我解决这个问题。

4 个答案:

答案 0 :(得分:1)

要使用服务,您需要使用在构造函数中使用的名称来注入服务:

this.values = this.service.get_data()

答案 1 :(得分:1)

由于在UsermasterComponent中,this.UsermasterService未定义。您将其声明为属性,但从不为其分配任何值。属性UsermasterService与类UsermasterService之间没有任何联系。

使用构造函数

  constructor(private service: UsermasterService) { }

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

答案 2 :(得分:0)

涉及两个步骤

(i)您需要在构造函数中注入服务

constructor(private userMasterService: UsermasterService) { }

(ii)调用该方法并订阅它,

this.values = this.userMasterService.get_data()

答案 3 :(得分:0)

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

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

  constructor(private http: HttpClient) { }

  //Since this service is about UserMaster, 
  //don't name the method as 'get_data' which is too generic.
  //better to have a separate class 'User' so that the returned
  //type is Observable<User>
  getUsers(): Observable<any> {        
     return this.httpClient.get('http://localhost/tasker/api/index.php/Welcome/get_data');    
  }    
}

export class UserMasterComponent implements OnInit {
  ..........
  constructor(private service: UsermasterService) { }

  ngOnInit() {
   //other source code

   //let component decide how to handle the returned data.
   this.UserMasterService.getUsers().subscribe(users => {
       this.values = users;
       console.log(this.values);
   });

  }
 }

再次,正如我在其他问题中所建议的那样-看一下诸如NSwag之类的代码生成工具,以自动生成这种类型的源代码(Xyz.service.ts)。