Reputation: 3889
I have an angular service that returns from the backend an Observable defined as:
GetAllMyResponses(): Observable<ResponsesGridResult> { ..... }
and the model is declared in the following way:
export class GridResult {
a: string;
b: Date;
c: string;
d: string;
}
export class ResponsesGridResult {
public rowCount: number;
public summaries: GridResult[];
}
So now when I go to use my method from my component I do:
private getResponsesSubscription : Subscription;
....
.....
this.getResponsesSubscription = this.myservice.GetAllMyResponses()
.pipe(delay(500))
.subscribe((result) => {
this.selected = result.summaries;
});
The issue I have is that
this.selected
declared as selected: responseSummary[] = [];
is a different type declared in the form:
export class responseSummary {
a: string;
b: Date;
c: string;
d: string;
e: string;
f: string;
}
export class ResponsesSummaryGridResult {
public rowCount: number;
public summaries: responseSummary [];
}
the responseSummary object holds all property names that are in GridResult plus extra.
So I cant do this.selected = result.summaries, because the returning object isn't the same as the object I'm trying to set. is there a way to Map one object onto the other? I cannot declare selected as the same type, because it's used in other parts of the system.
Upvotes: 0
Views: 2248
Reputation: 394
One possibility would be to map your array like so :
this.getResponsesSubscription = this.myservice.GetAllMyResponses()
.pipe(delay(500))
.subscribe((result) => {
this.selected = result.summaries.map( summary =>
({...summary, e: 'value', f: 'value'}) as responseSummary
)
});
If e
and f
can be undefined
then mark them as such :
export class responseSummary {
a: string;
b: Date;
c: string;
d: string;
e?: string;
f?: string;
}
This will simplify the code shown above to :
this.selected = result.summaries as responseSummary;
By the way, in your example, you define GridResult
, responseSummary
and ResponsesSummaryGridResult
as classes. Do you need to do so?
Upvotes: 1