On Angular I write in the html template this code:
<div *ngFor='let itemArray of myObservableArray'>
<div *ngFor='let item of itemArray | async'>
{{item.value}}
</div>
</div>
This is my app.component.ts:
import { Component } from '@angular/core';
import { MyService, MyDataType } from './app.service';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 5';
myObservableArray: Observable<MyDataType[][]>;
constructor(private myService: MyService) {
this.getData(2);
}
getData(id: number) {
if (!this.myObservableArray) {
this.myObservableArray = new Array<MyDataType[]>();
this.myObservableArray[id] = this.myService.getData(id);
}
}
}
And this is the code of the app.service.ts:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class MyService {
mydata: MyDataType[] = [
{"id":1, "value":"value_1_1"},
{"id":1, "value":"value_1_2"},
{"id":2, "value":"value_2_1"},
{"id":2, "value":"value_2_2"},
{"id":3, "value":"value_3_1"},
{"id":3, "value":"value_3_2"}
];
constructor() { }
getData(id: number):Observable<MyDataType[]>
{
let data = new Observable<MyDataType[]>(observer => {
setTimeout(() => {
observer.next(this.mydata.filter(i => i.id == id));
}, 4000);
});
return data;
}
}
export class MyDataType
{
public id: number;
public value: string;
}
The html template works correctly but I don't understand why the compiler give me this error:
Type 'MyDataType[][]' is not assignable to type 'Observable<MyDataType[][]>'.
Property '_isScalar' is missing in type 'MyDataType[][]'.
(property) AppComponent.myObservableArray: Observable<MyDataType[][]>
I think my initialization of the matrix is wrong but being quite new on Angular and TypeScript/JavaScript I would like help on how I can do it. On stackbliz I put the complete DEMO. Thanks.
myObservableArray: Observable<MyDataType[][]>;but then usethis.myObservableArray = new Array<MyDataType[]>();ObservableArraywhich would be used asmyObservableArray: ObservableArray<MyDataType[]>;