Error in Django & Angular 2: {_dataService is not defined}

I recently tried incorporating Angular 2 into my Django application as a frontend. However, I encountered an issue while attempting to create a GET request. Angular 2 kept throwing me an error that I couldn't paste here due to formatting constraints.

https://i.sstatic.net/oMmEh.png

These are the key files involved in setting this up:

html

{% extends 'profile/base_profile.html' %}

{% load humanize_tags %}
{% load article_tags %}
{% load staticfiles %}
{% block body %}

{% include '_includes/_article-modal-container.html' %}

<div class="container" style="border:1px solid #bfbfbf">

<!-- Load dependencies -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.1/es6-sham.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-polyfills.js"></script>
<script src="https://npmcdn.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e094999085938392899094a0d1ced7ced5">[email protected]</a>/lib/typescript.js"></script>
<script src="https://npmcdn.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f6858f8582939b9c85b6c6d8c7cfd8ce">[email protected]</a>/dist/system.src.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/Rx.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2.dev.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/http.dev.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/router.dev.js"></script>

<!-- User defined component -->

<http-app></http-app>
<script>
    System.config({
        transpiler: 'typescript',
        packages: {
            app: {
                format: 'register',
                defaultExtension: 'ts'
            }
        }
    });
    System.import('{% static '_dev/a2_get_post/app.component.ts' %}')
            .then(null, console.error.bind(console));

</script>


</div>
{% endblock body %}

app.component.ts

//import the Component and bootstrap from angular
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
import {DataService} from './data.service.ts';
import {error} from "util";
import {HTTP_PROVIDERS} from "angular2/http";
import {Injectable} from 'angular2/core'

@Component({
    selector: 'http-app',
    template: `
        <div>
            <div class="input">
                <label for="title">Title</label>
                <input type="text" id="title" #title>
            </div>           
            <div class="input">
                <label for="body">Body</label>
                <input type="text" id="body" #body>
            </div>          
            <div class="input">
                <label for="user-id">User ID</label>
                <input type="text" id="user-id" #userId>
            </div>    
            <button (click)="onPost(title.value, body.value, userId.value)">Post Data</button>
            <button (click)="onGetPosts()">Get All Posts</button>
            <p>Response: {{response}}</p>
        </div>
    `,
    providers: [DataService]
})

@Injectable()
export class AppComponent{
    response: string;

    constructor ( private _dataService: DataService) {
        console.log('Constructor:');
        console.log(this);
        console.log('');
    }

    onPost(title: string, body: string, userId: string) {
        console.log('onPost:');
        console.log(this);
        console.log('');
        const data = {
            title: title,
            body: body,
            userId: userId
        };
        this._dataService.postData(data)
            .subscribe(
                data => this.response = JSON.stringify(data),
                error => console.log(error)
            );
    }

    onGetPosts() {
        console.log('onGetPosts:');
        console.log(this);
        console.log('');
        this._dataService.getData()
            .subscribe(
                data => {
                    response = JSON.stringify(data);
                },
                error => console.error(error)
            )
    }

}

bootstrap(AppComponent, [HTTP_PROVIDERS]);

data.service.ts

import {Injectable} from "angular2/core";
import {Http, Headers} from "angular2/http";
import 'rxjs/Rx';
import {Observable} from "rxjs/Observable";

@Injectable()
export class DataService {
    constructor (private _http: Http) {

    }

    postData(data: any): Observable<any> {
        const body = JSON.stringify(data);
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this._http.post('<REMOVED>', body, {headers: headers})
            .map(response => response.json());
    }

    getData(): Observable<any> {
        console.log(this);
        return this._http.get('<REMOVED>')
            .map(response => response.json());
    }
}

Technologies used: Django 1.9.6, Angular 2 Beta 17, Python 3.4.3

Looking for any guidance or suggestions!

Answer №1

It's recommended to utilize the variable this._dataService instead of directly using the type DataService

this._dataService.postData(data)
 .subscribe(
      data => this.response = JSON.stringify(data),
      error => console.log(error)
);

this._dataService.getData()
  .subscribe(
    data => {
        response = JSON.stringify(data);
    },
    error => console.error(error)
)

For more reference, check out the related plnkr https://plnkr.co/edit/WemJ7qotAISH1mBvraiD?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most efficient way to retrieve a document from pouchdb that includes the revision attribute?

I am currently developing an application using the electron framework and integrating pouchdb. As certain values in my database are dynamic and constantly changing, I am looking for a way to track these changes without having to create new documents for ea ...

Using Selenium WebDriver in JavaScript to Extract Text from an Array

During my experimentation with Selenium webdriver in javacript, I encountered a challenge when trying to extract text from an array of WebElements (specifically cells within a table). The usual command getText() did not work as expected when attempting to ...

Converting PDF files to JSON in ASP.NET and transferring them to AngularJS using Base64 does not result in identical files

After encoding a PDF file as Base64 and assigning it to a property of my model object in ASP.NET WEB API, the JSON response is received by my AngularJS client application. However, upon saving the file, I noticed that the file size increases by one and 1/3 ...

Utilizing HTML to emphasize a section of text

Hey there! I have a question related to an image with unicodes. The letter featured in the image was written using unicode characters పా. I'm trying to highlight the white portion of the image, but simply replacing it with ా isn&apos ...

The error message displayed in app.js is: TypeError - it is not possible to call the 'query' method on null

Recently, I started working with node.js and encountered an issue while trying to load CSV file values into a database. The error message displayed is as follows: Error: at var stream = client.query(copyFrom('COPY menu_list FROM STDIN')); T ...

Send the film to Cloudinary from within an AngularJS single page application running within Electron

Currently, I am facing a challenge in my electron app which is an AngularJS SPA. I want to upload a file from the user's disk to Cloudinary directly from the front-end. In the past, I was successful in uploading photos from AngularJS by selecting the ...

Utilize JavaScript to parse and retrieve specific data from an SVG file in XML format

I am attempting to retrieve an svg file using jquery or javascript. Here is an example of the svg code: <svg width="111" height="123" xmlns="http://www.w3.org/2000/svg"> <g> <title>Layer 1</title> <rect fill="#ffffff" strok ...

Steps for selecting checkboxes according to database values in AngularJSWould you like to learn how to automatically check checkboxes based on the

I am experiencing an issue where I can successfully insert values into the database based on what is checked, but I am encountering difficulty retrieving the values when fetching from the database. Can anyone provide me with some assistance? Thank you. Th ...

Can I retrieve the count of pixels below a certain threshold value using WebGL/OpenGL?

class WebGLProcessor { initializeGLContext = (canvas, version) => { canvas.width = window.innerWidth * 0.99; canvas.height = window.innerHeight * 0.85; var gl = canvas.getContext(version ? 'webgl' : 'webgl2&apo ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...

Optimal Method for Updating Tags Across Three Tables in Node.js and MySQL

Currently working on developing an application that allows users to create and share content, referred to as "moments", along with relevant tags. Utilizing a MySQL database, I have designed a 3-table data model structured as follows: Table: MOMENTS, Col ...

Unable to view image when using material-ui CardMedia component

Hello, I've encountered a problem with rendering an image in my application. Let me explain the issue in a simplified manner. So, I have a card component (MyCardComponent) where I need to pass a string prop containing the image file location. The goa ...

Utilize PHP, JSON, and JavaScript to dynamically insert personalized information into HTML

Struggling, I turn to this site for help despite the dislike for "spot my mistake" code. My website urgently needs access to user-specific data from a PHP database, then convert that data into a JSON file and display it in an HTML header. The database cont ...

My function doesn't seem to be cooperating with async/await

const initialState={ isLoggedIn: false, userData: null, } function App() { const [state, setState]= useState(initialState) useEffect(()=>{ async function fetchUserData(){ await initializeUserInfo({state, setState}) // encountering an ...

While the AWS CodePipeline is executing the script, an error is appearing in the log. Please address this issue and resolve it

This is the content of buildspec.yml: version: 0.2 phases: install: commands: - npm install -g typescript pre_build: commands: - echo Installing source NPM dependencies... - npm install build: commands: - echo Bui ...

Converting to alphanumeric characters using JavaScript

Is there a way to efficiently encode a random string into an alphanumeric-only string in JavaScript / NodeJS while still being able to decode it back to the original input? Any suggestion on the best approach for this would be greatly appreciated! ...

Typescript: Retrieve an interface containing properties that are found in interface A, but not in interface B

I am currently developing a mapper that will facilitate the translation between a serialized entity state and a form state. In the context of two given interfaces A and B, I am exploring ways to derive a third interface C that includes properties present ...

The failure of the Selenium script can be attributed to the presence of the AJAX

Struggling to automate an application with an AJAX loader causing issues? Getting the dreaded error message about element not being clickable when the loader is active? Frustrating, right? But fear not! I have devised a clever solution in the form of a wr ...

Send the JSON output to the controller function

Hello there! I am new to asp.net mvc and I'm looking for a way to pass JSonResult data to a controller method. In my View, I have set up a table like this: <table id="tbl_orderItems" class="table table-striped table-bordered table-hover dt-respo ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...