1

I'm learning angular and for best practice I think I need to add an interface to the output. The service DataFetchService is taking objects from an internal .json file. What is the best way to implement my interface to this code? Any resources on the matter are more then welcome

import { Component, OnInit } from '@angular/core';
import { DataFetchService } from '../userActions';

interface getDataInterface {
  name: string;
  surename: string;
  }

@Component({
  selector: 'app-data-from-server',
  templateUrl: './data-from-server.component.html',
  styleUrls: ['./data-from-server.component.css']
})
export class DataFromServerComponent implements OnInit {

  users$: Object;

  constructor(private data: DataFetchService) { }

  ngOnInit() {
    this.data.getData().subscribe(
      data => this.users$ = data
    )
  }
}

1 Answer 1

1

Just to be super clear, interfaces are not present in the transpiled JS. If you need it to then you need an abstract class.

That said the purpose of an interface in cases like this is to provide type safety, so you should be strongly typing your data:

users$: getDataInterface; //Could be getDataInterface[] based on the names...
constructor(private data: DataFetchService) { }

ngOnInit() {
this.data.getData().subscribe(
  (data: getDataInterface) => this.users$ = data
  )
}

As an aside; classes and interfaces typically use PascalCase in TypeScript so your interface should be GetInterfaceData

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.