Filipe Costa
Filipe Costa

Reputation: 189

Using interface with angular 2

i am confused on how to use interface with angular, basicly i am declaring a interface like this:

export interface IStatus {
    fVBackward: boolean,
    fVForward: boolean,
    sVBackward: boolean,
    sVForward: boolean
}

public vStatus: IStatus = null;

basicly i am setting the interface data onInit of the component but inside a promise, the thing is that i get a error on the template because the IStatus is null, i want to make the changes and then check it on the template, any advice?

Upvotes: 0

Views: 55

Answers (3)

Haifeng Zhang
Haifeng Zhang

Reputation: 31895

basicly i am setting the interface data onInit of the component but inside a promise, the thing is that i get a error on the template because the IStatus is null

Use async:

Based on your description, It's not really an interface issue. You didn't get the status values from Promise yet. You can use async to solve it

status.service.ts

 getStatus() : Observable<IStatus> {
    return this.http.getStats(URL);
  }

status.component.ts

 ngOnInit() {
   // it's observable
   iStatus:Observalbe<IStatus> = this.statusService.getStatus(); 
 }

In the template, you should do something like:

<p> {{ iStauts | async }} </p>

Alternativley, you can do:

<p> {{ iStatus?. fVBackward }}</p>

Use ? check the object is ready or not, it only invoke fVBackward once iStatus is available.

Interface: What interface does is restrict the properties in your object, for instance:

export interface Person{
    name: string;
    age: number;
}

aPerson: Person = {name: 'Arron', age: 23}; // this is correct
anotherPerson: Person = {name: "Bill"};  // not okay, property age is missing
thatPerson: Person = {"name": "Chris", age:24, gender:"Male"};  // not okay, property gender is not declared in interface Person

Upvotes: 0

Herbert Corazao
Herbert Corazao

Reputation: 41

Declare the variable like this inside the component you want to use:

public vStatus: IStatus = <IStatus>{};

What you are doing is initializing the variable with as an empty IStatus object. You can then assign the values as you find it convenient.

Upvotes: 1

Hugo Noro
Hugo Noro

Reputation: 3243

You should not use null on TypeScript. It’s not recommended by the TypeScript guidelines. You can find a bit more information here (including the link for Microsoft guidelines)

You should use undefined or simply declare the variable without initialisation

public vStatus: IStatus;

Even the public modifier is not needed because it’s public by default on TypeScript but it will not throw an error if you use it.

If you’re having problems on the template by trying to access properties of the vStatus before it’s available you can use the safe navigation in the template

vStatus?.fVBackward

That means that as soon as the vStatus is available it will render the property after the dot

Upvotes: 0

Related Questions