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

问题描述 投票:0回答:4

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

零件

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

angular service components
4个回答
1
投票

因为在UsermasterComponentthis.UsermasterService是未定义的。您将其声明为属性,但从不为其指定任何值。物业UsermasterService和班级UsermasterService之间没有任何联系。

用构造函数

  constructor(private service: UsermasterService) { }

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


1
投票

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

this.values = this.service.get_data()

0
投票

涉及两个步骤,

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

constructor(private userMasterService: UsermasterService) { }

(ii)致电方法并订阅,

this.values = this.userMasterService.get_data()

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)。

© www.soinside.com 2019 - 2024. All rights reserved.