Reputation: 14185
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
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 :
export class MyClass {
data: MyData;
constructor(private dataService: DataService) {
this.dataService.getData().subscribe((myData) => {
this.data = myData;
});
}
}
AsyncPipe
in your templateexport 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
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