angler
angler

Reputation: 99

Angular multiple services in one component

Welcome to the latest edition of An Angular Newbie Asks a Stupid Question!

I have an In-Memory-Data-Service set up in lieu of connecting my web services. I have two arrays, Users and UserData, defined in the In-Memory-Data-Service. I don't know how to use both in the same component html template.

In the Src directory I have a service.ts set up for both but I still can't figure out how to use both in the same component.

Upvotes: 3

Views: 11712

Answers (2)

Mithil Mohan
Mithil Mohan

Reputation: 243

I don't know how your code is, I'm providing a noob level example for a simple service

//Service.ts

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

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

  private users=['a','b','c'];
  private userData=['x','y','z'];

  constructor() { }

  getUsers():<any>
  {
    return this.users;
  }

  getUserData():<any>
  {
    return this.userData;
  }


}

//Component.ts

import { Component, OnInit} from '@angular/core';
import { Service } from '../Service.ts';

@Component({
  selector: 'app-account-detail',
  templateUrl: './account-detail.component.html',
  styleUrls: ['./account-detail.component.css']
})
export class AccountDetailComponent implements OnInit {

 public userArr,userDataArr;
  constructor(private service:Service) { }

  ngOnInit() {





    this.userArr= this.service.getUsers();
    this.usersDataArr = this.service.getUserData();




  }

}

Upvotes: 2

Ans Bilal
Ans Bilal

Reputation: 1067

To use one or more service(s) in your component you will need to Import that service in that component like

import { MyService1 } from '../services/MyService1.service';
import { MyService2 } from '../services/MyService2.service';

then you need to inject these service in constructor

constructor(private myService1: MyService1, private myService2: MyService2) { }

Upvotes: 13

Related Questions