简体   繁体   中英

Angular 2 Handle data Asynchronous

I´m quite new to Angular 2 and I have a little Problem: I load data from a service asynrochnus. The data arrives in my component and i can handle with it. Here i save the data in a local variable.

Here´s the code from the component:

export class ConfigurationComponent implements OnInit {

    private tab: string = 'general';
    private config = [];

    constructor(private router: Router, private variables: Variables, private apiService: ApiService) {
        if (!this.variables.getIsLoggedIn()) {
            this.router.navigate(['login']);
        }
    }

    ngOnInit() {
        this.getConfigService();
    }

    getConfigService() {
       this.apiService.getConfigService().
        subscribe(
            data => {
                this.config = data.settings.section;
            },
            //error => this.error = <any>error,
            error => this.variables.setFailure(error)
            //() =>  console.log('done:' + this.status)
         );
    }

And here´s the code in html:

<th>{{config[5].entry.name}}</th>
<th>{{config[5].entry.text}}</th>

The problem is, that on the time when the view loads, the local variable 'config' is just '[]'. So the 'config[5]' fails. But if i do not define the local variable in the component, it fails, too.

Can someone help me here?

Thanks!

You should push each of elements from data.settings.section into your config and check it does exist in view;

//in component
data.settings.section.forEach(i => this.config.push(i));

//in html
<div *ngIf="config[5]">
     {{config[5].entry.name}}
</div>

I hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM