如何将API中的数据加载到Angular 2中的数组中?

时间:2017-09-21 00:04:20

标签: javascript angular typescript

所以上周我开始学习AngularJS,只是意识到我最好还是学习Angular 2。在对Plunker上的示例应用程序进行了大量阅读和修补之后,我终于准备好深入研究Angular 2.上周,通过AngularJS,我能够创建一个简单的应用程序,从API中检索数据并将其转换为导航菜单。所以本周我试图将该代码移植到Angular 2。

我不能说这很容易,但经过多次摆弄后我发现它不起作用的原因是它甚至没有提取数据。下面是我提取数据的服务代码。

./src/app/navigation.service.ts

import { NavItem } from './navigation.model';
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class NavService {   
    sections: NavItem[] = [];
    categories: NavItem[] = [];

    constructor(private http: Http) {
    }
    loadSections() {
        //var headers = new Headers();
        //headers.append('Content-Type', 'application/json');
        this.http
            .get('http://localhost:15557/api/navigation/sections/list')
            .map(res => {
                return res.json()
            })
            .subscribe(
            data => {
                this.sections = data;
            },
            err => this.logError(err),
            () => console.log("Loaded all sections")
        );
    }

    loadCategories(id) {
        this.http
            .get('http://localhost:15557/api/navigation/categories/' + id)
            .map(res => res.json())
            .subscribe(
            data => this.categories = [data],
            err => this.logError(err),
            () => console.log("Loaded categories in section with id " + id)
        );
    }

    logError(err) {
        console.error('There was an error: ' + err);
    }
}

./src/app/navigation.model.ts

export class NavItem {
    // I am never going to use int unless I need to do math operations //
    id: string;
    name: string;
    pid: string;
    slug: string;

    constructor(id: string, name: string, pid: string, slug: string) {
        this.id = id;
        this.name = name;
        this.pid = pid;
        this.slug = slug;
    }
}

./src/app/navigation.component.ts

import { Component } from '@angular/core';
import { NavItem } from './navigation.model';
import { NavService } from './navigation.service';

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.css']
})

export class NavComponent {
    public section: NavItem;
    constructor(private service: NavService) { }
    ngOnInit() {
        this.service.loadSections();
    }
}

这段代码我做错了什么?

1 个答案:

答案 0 :(得分:1)

我之前从未使用过这样的服务。也许你的实现有一个简单的错误,但这是我总是以角度实现服务的方式。 :)

服务

getSomething() {
    return this.http.get('your-api-url').map(res => {
       return res.json()
    });
}

组件

makeRequest() {
    this.service.getSomething().subscribe(data => {
        this.variable = data;
    }, err => {
        console.log("error :/");
    });
}