0

Below is the code to get the json data

    export class AppComponent  implements OnInit {
          observableBooks: Observable<Book[]>
          books: Book[];
          errorMessage: String;
          constructor(private bookService: BookService,private loki: LokiService) { }
          ngOnInit(): void {
               this.observableBooks = this.bookService.getBooksWithObservable();
               this.observableBooks.subscribe(
                   books =>  this.books = books,
                   error =>  this.errorMessage = <any>error);

        this.observableBooks.forEach(element => {
          console.log(element);/// here I can get the json format as expected

// console.log(element.fname); //this is not working
//  console.log(element.lname);// this is not working
        });

      }
    }

Consider the json as like below

[{fname: "name1",lname: "name2"},{fname: "name3",lname: "name4"}]

I want to get the values of fname and lname.

Can anyone help me?

8
  • That's not valid JSON. Is this an array of objects?, Then it should be enclosed in []. Commented Oct 29, 2017 at 13:36
  • Have you tried console.log(element[0].fname) ? Commented Oct 29, 2017 at 13:37
  • yes, it is a array of object Commented Oct 29, 2017 at 13:37
  • What does "//this is not working" mean exactly anyway? Commented Oct 29, 2017 at 13:37
  • @GünterZöchbauer, the problem is I can't use any json object name. If I use the applications show the below error Property 'fname' does not exist on type 'Book'" Commented Oct 29, 2017 at 13:40

1 Answer 1

1

confirm if you have these 2 properties inside your book model

export class Book{
  fname: string;
 lname: string;
}

and try this

this.observableBooks.subscribe(books => { 
          this.books = books,
          this.books.forEach(element => {
               console.log(element.fname);
               console.log(element.lname);
           })
          error =>  this.errorMessage = <any>error
 });
Sign up to request clarification or add additional context in comments.

Comments

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.