0

I have web api action method returning chapterid and chaptername. I want to map this to angular class with an extra field of 'Edit' whose default value is false

export class Chapter {
  chapterid: number;
  chaptername: string;
  Edit: boolean = false;
}

 public Chapters: any;

this.http.get<Chapter>(this.baseUrl + 'api/Chapters').subscribe((response) => { this.Chapters = response; console.log(this.Chapters); }, error => console.log(error));

I am not getting the extra field 'Edit'.

2
  • the typings for this response basically disappear once the application is transpiled. They are just for you, the developer to make your life easier during development, they will not automagically modify a response to have extra fields. You need to instantiate and set those fields manually. You can set a constructor on your class and use that to populate the extra fields, but otherwise it will not work as you intend. Commented Jul 10, 2019 at 17:54
  • i tried by changing my class as below. export class Chapter { chapterId: number; chapterName: string; Edit: boolean; constructor(chapterId: number, chapterName: string) { this.chapterId = chapterId; this.chapterName = chapterName; this.Edit = false; } But it didn't work. Am i doing correct? Commented Jul 10, 2019 at 19:29

1 Answer 1

1

Looks like API api/Chapters returns array of objects which has chapterid and chaptername. If this is true then update your code like this:

this.http.get<Chapter[]>(this.baseUrl + 'api/Chapters')
                 .pipe(
                     map(chapters => {
                         return chapters.map(c => {return {...c, Edit: false}});
                     }),                     
                 )
                 .subscribe((response) => { this.Chapters = response; console.log(this.Chapters); }, error => console.log(error));
Sign up to request clarification or add additional context in comments.

1 Comment

It worked. One return is missing in your solution. this.http.get<Chapter[]>(this.baseUrl + 'api/Chapters').pipe(map(chapters => { return chapters.map(c => { return { ...c, Edit: false } } ) })).subscribe(val => console.log(val));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.