0
export class MyClass {
    data: MyData;  
    constructor(private dataService: DataService) {    
      this.data = this.dataService.getData(); // error             
    }
}


export class DataService{
    data: MyData; 
     constructor(private http: Http) { }

    getData(): Observable<MyData>{
       return Observable.from([this.fakeData()]
          .map(res=>res as MyData));
    }   

    private fakeData() : MyData {   
       ...  
    }
}

I'm getting error on line

 this.data = this.dataService.getData()

Type Observable is not assignable to MyData

Noémi Salaün
  • 4,866
  • 2
  • 33
  • 37
user1765862
  • 13,635
  • 28
  • 115
  • 220

2 Answers2

1

Typescript is right.

In your component, you said that data is supposed to be a MyData object. Then, in your constructor you call your service that returns an Observable of MyData and you try to assign its result to your attribute data.

That's not how Observable works.

Here, you have two simple solutions :

Subscribing to your observable

export class MyClass {
    data: MyData;  
    constructor(private dataService: DataService) {    
      this.dataService.getData().subscribe((myData) => {
        this.data = myData;
      });  
    }
}

Or using the AsyncPipe in your template

export class MyClass {
    data$: Observable<MyData>; // Change the type here.
    // The $ suffix is a convention to tell that
    // this attribute is an observable.

    constructor(private dataService: DataService) {    
      this.data$ = this.dataService.getData();  
    }
}

And then, in your template you can use data with the AsyncPipe

<div>
    <some-component [someData]="data$ | async"></some-component>
</div>
Noémi Salaün
  • 4,866
  • 2
  • 33
  • 37
0

try this, declare data as observable of MyData

export class MyClass {
  data: Observable<MyData>;   
 constructor(private dataService: DataService) {    
   this.data = this.dataService.getData(); // error             
 }
}
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52