2016-04-25 74 views
2

我在我的html pages中使用angular2作爲前端。我有一個使用postgresql的django項目。 在django項目中使用angular2連接到django模型和數據庫以執行像Read,Update等基本操作(CRUD)的最佳方法是什麼?Django + Angular2:如何從數據庫中獲取數據?

目前我需要從數據庫中動態獲取數據。 (例如,如果用戶從產品列表中單擊產品,則應從數據庫中檢索產品詳細信息並將其顯示給用戶)

任何建議或參考示例鏈接都將有所幫助。

回答

3

創建REST API端點(使用DRF標準的REST API的或者只是使用香草的Django生成的請求JSON響應,並稱之爲REST API)。

對於前: /product/:id是您創建Django中獲取特定產品的細節

然後用角來請求throught這些API和得到的答覆,並做任何你想用的API終點該數據。

對於前: 進行GET請求/product/1PK = 1獲取產品的詳細信息,當用戶點擊該產品。

Browse through Github有些啓發。

1

結帳django-rest-framework

DRF是一個Django應用程序,使其餘的建設應用程式變得輕而易舉。 檢出他們的quick tutorial以瞭解如何在項目中使用DRF。使用Django

0

我最近正在研究類似的項目。我的方法就像上面提到的@ praba230890一樣。

這裏有一些樣品...

Django的

在views.py

class HView(APIView): 
    def get(self, request, format=None): 
    request_hero_id = request.query_params.get('id', None) 
    if request_hero_id: 
     return Response(
     { 
      'id': 1, 
      'name': 'test', 
      'position': 'mid' 
     }, 
     status=status.HTTP_200_OK 
    ) 
    return Response(
     { 'error': 'does not exist' }, 
     status=status.HTTP_404_NOT_FOUND 
    ) 

class HsView(APIView): 
    def get(self, request, format=None): 
    return Response(
     [ 
     { 
      'id': 1, 
      'name': 'test', 
      'position': 'mid' 
     }, 
     { 
      'id': 2, 
      'name': 'test', 
      'position': 'mid' 
     } 
     ], 
     status=status.HTTP_200_OK 
    ) 

在urls.py

urlpatterns = [ 
    url(r'^admin/', admin.site.urls), 
    url(r'', include('shweb.urls')), 
] 

您需要安裝django-cros-headers如果遇到CROS錯誤。此外,您將需要配置settings.py

Angular2

在API-service.service.ts

import { Injectable } from '@angular/core'; 
import { Http, Headers } from '@angular/http'; 

import 'rxjs/add/operator/toPromise'; 

import { Hero } from '../utils/hero'; 

@Injectable() 
export class ApiService { 
    /** Modify this later */ 
    private backend_api_url: string = 'http://localhost:8000/api/'; 
    private api_headers: Headers = new Headers(
    { 'Content-Type': 'application/json' } 
); 

    constructor(private http: Http) { } 

    getHero(id: number): Promise<Hero>{ 
    const url = `${this.backend_api_url}htest/?id=${id}`; 

    return this.http.get(url).toPromise().then(
     response => response.json() as Hero 
    ).catch(this.handleError); 
    } // END getHero 

    getHeroes(): Promise<Hero[]>{ 
    const url = `${this.backend_api_url}htests`; 
    console.log(url); 
    return this.http.get(url).toPromise().then(
     response => { 
     console.log(response.json()); 
     return response.json() as Hero[]; 
     } 
    ).catch(this.handleError); 
    } // END getHeroes 

    private handleError(error: any): Promise<any>{ 
    console.error('An error occurred', error); // TODO: update this 
    return Promise.reject(error.message || error); 
    } 
} 

在英雄。TS

export class Hero{ 
    id: number; 
    name: string; 
    position: string; 
} 

在你的組件文件,注入API服務到組件

@Component({ 
    selector: 'app-dashboard', 
    templateUrl: './dashboard.component.html', 
    styleUrls: ['./dashboard.component.css'] 
}) 
export class DashboardComponent implements OnInit{ 
    title: string = 'Dashboard'; 
    heroes: Hero[] = []; 

    constructor(private apiService: ApiService){} 

    ngOnInit(): void{ 
    this.getHeroes(); 
    } 

    getHeroes(): void{ 
    this.apiService.getHeroes().then(heroes => this.heroes = heroes); 
    } // END getHeroes 
} 

基本上,使用API​​來獲取數據,並鑄成類;那麼,你可以使用這些數據。

PS。我沒有觸及證書和安全部分。我相信你需要爲安全的API通信實施某種認證。 (在我的情況下,只允許GET,因此,我把安全部分放在後面。)

希望這會有所幫助!