0

Im trying to use a service i made from a component.

I have the following service:

import { Injectable } from '@angular/core';
import { PicItem } from './Models/Pictures';

@Injectable()
export class PicturesService {

  private readonly time = 10000;
  public image1:string = "";
  public image2:string = "";
  private _picList: string[];
  private index: number = 0;

  constructor() { 
       this._picList = [
       "",
       ""
  ]

      setInterval(() => {
        this.image1 = this.getImage();
        this.image2 = this.getImage();
      }, this.time);
  }

 getImage(){
    return this._picList[this.index++];
  }

}

This service should switch two pictures url in image1 and image2.

So now i have a component which i want to call this service, and get the urls form image1 and image2.

What is the correct way to use image1/2 urls inside the components html file?

I tried doing something like

<img src = {{image1}}>

But it doesn't seem to work.

Thanks.

EDIT:

In the component i get the image like so:

export class GalleryComponent implements OnInit {

  constructor(public pictureService: PicturesService) { 
    var pic1 = this.pictureService.image1;
  }

Which to my understanding, gets back the value of image1 from the service.

The problem is how to use this value inside the HTML file.

3
  • 1
    image1 needs to be a property of the component, not of the service. When you call the service from the component, you assign the return value of getImage() to the component's property image1 Commented Apr 9, 2018 at 15:16
  • I edited the questions. I dont believe that is the case. Commented Apr 9, 2018 at 15:20
  • Not var pic1, but probably this.image1=... in ngOnit (preferably) and declare it above constructor Commented Apr 9, 2018 at 15:28

1 Answer 1

1

you can use component attributes in the template:

export class GalleryComponent implements OnInit {
  pic1:any;
  constructor(public pictureService: PicturesService) { 
    this.pic1 = this.pictureService.image1;
  }

or use the service in template:

<img src="{{pictureService.image1}}">
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.