2

I am using angular2 as a front end in my html pages.I have a django project that uses postgresql. Which is the best approach to use the angular2 in the django project to connect to the django models and the database to perform basic operations(CRUD)like Read,Update etc?

Currently I need to fetch the data from the database dynamically. (e.g.If user clicks on the product from the product list then product details should be retrieved from the database and it is shown to the user)

Any advice or reference example link will be helpful.

3 Answers 3

3

Create REST api end points using Django (use DRF for standard REST api's or just use vanilla django to generate json response for the requests and call it REST api).

For ex: /product/:id is the api end point you've created to fetch the details of a particular product in Django

Then use Angular to request throught those API's and get the responses and do whatever you want with that data.

For ex: make a get request to /product/1 to fetch the details of a product with PK = 1 when the user clicks that product.

Browse through Github for some inspiration.

Sign up to request clarification or add additional context in comments.

Comments

1

Checkout django-rest-framework

DRF is a django app that makes building ReST apps a breeze. Checkout their quick tutorial to get a sense of how to use DRF in your project.

Comments

0

I'm recently working on the similar project you have. My approach is just like @praba230890 mentioned above.

Here are some samples...

Django

In 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
    )

In urls.py

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

You will need to install django-cros-headers if you run into CROS errors. Also, you will need to configure your settings.py

Angular2

In 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);
  }
}

In hero.ts

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

In your component file, inject the api-service into component

@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
}

Basically, using API to retrieve data and cast into class; then, you can use those data.

PS. I haven't touched the credentials and security part. I believe you need to have some sort of Authentication implemented for secure API communication. (In my case, only GETs are allowed. Therefore, I put the security part for later.)

Hope this would help!

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.