user1765862
user1765862

Reputation: 14185

Type Observable<MyData> is not assignable to MyData

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

Upvotes: 0

Views: 59

Answers (2)

No&#233;mi Sala&#252;n
No&#233;mi Sala&#252;n

Reputation: 5036

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>

Upvotes: 1

Fateh Mohamed
Fateh Mohamed

Reputation: 21387

try this, declare data as observable of MyData

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

Upvotes: 0

Related Questions