Issue
Seems like it should be easy
I would like to assign the value of p.message to a class variable.
export class Person {
id: number;
fName: string;
message: string;
}
Service:
personById(id: number): Observable<Person> {
let params = new HttpParams();
params = params.append("id", id);
return this.http.get(this.url + 'person', {
params: params,
observe: 'response'
}).pipe(
map(r => {
return r.body as Person;
})
);
}
component:
onSubmit(): void {
this.personService.personById(this.fg.controls['id'].value).subscribe(p => {
const x = p.message;
console.log("x=", x);
console.log("p=", p);
this.message = p.message;
console.log("message=", this.message);
this.myPerson = p;
console.log("myPerson=", this.myPerson);
this.message = this.myPerson.message;
console.log("message=", this.message);
console.log("message x=", p['message']);
console.log("here");
});
}
in chrome devtools I can see the value of p.message by highlighting and this.myPerson obtains all the properties and values of p. need to know how to set the value of some variable with the value of p.message.
in devtools when I do console.log(p[0].message) I do see the value I want but VSC complains about the line
console.log(p[0].message);
with a message of
Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'Person'. Property '0' does not exist on type 'Person'.ts(7053)
so somehow need to drill into p to obtain the value of message.
found if I changed the service to
personById(id: number): Observable<Person[]> {
let params = new HttpParams();
params = params.append("id", id);
return this.http.get<Person[]>(this.url + 'person', {
params: params,
observe: 'response'
}).pipe(
map(r => {
return r.body as Person[];
})
);
}
I can then access the value of message. but what is unclear is I am using a key value so not getting a Array of Persons. how would I change the service to return an Observable of Person not a Person[]?
Solution
I think your api is returning an array, if you dont want an array, but a single value, just get the first element and return it.
personById(id: number): Observable<Person> {
let params = new HttpParams();
params = params.append("id", id);
return this.http.get<Person[]>(this.url + 'person', {
params: params,
observe: 'response'
}).pipe(
map(r => {
return (r.body && r.body[0]) as Person; // <- changed here
})
);
}
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.