A
A
Artem00712017-02-02 11:46:29
JavaScript
Artem0071, 2017-02-02 11:46:29

How to loop through an array of an object?

Good afternoon!
The component has a Blog
object . In the html output:

<div *ngFor="let oneBlog of Blog.Blog">
    <p>Опубликовано - {{oneBlog.Release}}</p>
</div>

Everything works perfectly. But this doesn't work if there is only one element in the Blog.
How can I display only one element?
Been like this:
<div>
    <p>Опубликовано - {{Blog.Blog[0].Release}}</p>
</div>

But it throws an error:
EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/pages/post/post.component.html:8:27 caused by: undefined is not an object (evaluating 'self.context.Blog.Blog')

Blog in the first variant:
92d8f3b5d21f4790b3e073d11fae9ef8.png
Blog in the second variant:
be22e0a477754c8db07cac66e3ff0d9a.png
The component itself:
import { Component, OnInit} from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import { Response} from '@angular/http';
import { HttpService} from '../../services/http.service';

@Component({
    moduleId: module.id,
    selector: 'post-app',
    templateUrl: 'post.component.html',
    providers: [HttpService]
})
export class PostComponent implements OnInit {
    Blog = [];
    id;
    constructor(private activateRoute: ActivatedRoute,private httpService: HttpService){
        this.id = activateRoute.snapshot.params['id'];
    }

    ngOnInit(){
        this.httpService.getOnePost(this.id).subscribe((data: Response) => this.Blog=data.json());
    }
}

ADDITION
I added a button to the html:
<button (click)="testMe()">Test</button>
And I wrote in the component:
testMe(){
        console.log(this.Blog.Blog.Release);
    }

And now, if you press the button, it displays the correct date in the console. But it gives an error in html

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander Manakov, 2017-02-02
@gogolor

I would leave the template as it is (with Array), and in the controller I would do this:
In general, if there is access to the backend, then I would redo it so that the method instead of Blog returns Blogs when there are a lot of them

A
Aleksei Podgaev, 2017-02-02
@alexiusp

A little more data is needed. Blog is just an object or a Promise? What is Blog.Blog? When and how is this property initialized?

A
Alexander Belov, 2017-02-02
@AlexanderBelov

If you try like this?

<div *ngFor="let oneBlog of Blog.Blog">
    <p *ngIf="Blog.Blog?.length > 0">Опубликовано - {{oneBlog.Release}}</p>
</div>

A
Artem Komarov, 2017-02-02
@m0sk1t

You have different types... In the first case Blog is Array and in the second case Object, you can see in the screenshots
Published - {{Blog.Blog[0].Release}}
Should be replaced with
Published - {{Blog.Blog.Release}}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question