Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JQuery AJAX call to Angular 2 service

I was using JQuery for http requests to .NET controllers (I'm using .NET MVC 4.5.2), but am now starting to use Angular 2, so I want to handle those JQuery AJAX calls with Angular 2 instead. Here is the JQuery I was using before, which worked just like I wanted:

$.get('/Plan/Variety/ListVarietiesInMenuForSelling')
    .done(function(data){
        console.log(data)
    });

How do I set up my Angular 2 service to accomplish the same thing? I've tried the code below:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';  

@Injectable()
export class SellingMenuVarietiesService {
    private url = '/Plan/Variety/ListVarietiesInMenuForSelling';  // URL to web api    

    constructor(private http: Http) { }

    getVarieties() {
        return this.http.get(this.url);
    }       
}

Unfortunately this doesn't work. Instead, I get this error in the console:

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property '0' of undefined        core.umd.js:3462

The only examples I've been able to find handle JSON data and then use Angular to parse the data and format it into HTML. My controller already returns the HTML I need, so I don't need Angular to parse JSON. How do I get the http request to work like it did when I was using JQuery?

Just to be clear, for testing purposes I changed return this.http.get(this.url); to return '<h1>test data</h1>'; and was able to get that to display correctly, so I know that the only issue is with the http request.

EDIT: Here is the code where I call getVarieties():

export class SellingMenuVarietiesComponent implements OnInit {   
    varietyListSelling: any;    

    constructor(
        private router: Router,
        private sellingMenuVarietiesService: SellingMenuVarietiesService) { }    

    ngOnInit(): void {        
        this.varietyListSelling = this.sellingMenuVarietiesService.getVarieties();
        console.log('initializing SellingMenuVarietiesComponent');
    }
}

And here is how I bind it to the HTML:

<div [innerHtml]="varietyListSelling"></div>

I used that instead of {{varietyListSelling}} because I need the string to be converted to HTML.

UPDATE

I upgraded TypeScript and removed my InMemoryWebApiModule and InMemoryDataService imports from app.module.ts, which is resulting in a new error. The error now says: EXCEPTION: Unexpected token < in JSON at position 4

Is this because we are turning my HTML data into JSON? How can I just return the HTML like my JQuery was doing?

like image 896
Bryan Avatar asked Oct 30 '22 18:10

Bryan


2 Answers

You could do something like this:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class SellingMenuVarietiesService {
    private url = '/Plan/Variety/ListVarietiesInMenuForSelling';  // URL to web api    

    constructor(private http: Http) { }

    public getVarieties(): Observable<any> {
        return this.http.get(this.url).map(response=>{return response});
    }       
}

then to consume the service:

 this.sellingMenuVarietiesService.getVarieties().subscribe(res => {
    console.log(res);
    });

Update:

The html you are trying to render is not rendering because the request has not completed when the template is being rendered. A possible solution for this is to add an ngIf to the div tag.

div *ngIf="varietyListSelling" [innerHtml]="varietyListSelling"></div>
like image 81
Eduardo Dennis Avatar answered Nov 15 '22 05:11

Eduardo Dennis


You must subscribe to really send the request and read the response.

getVarieties() {
        return this.http.get(this.url).map((response: Response) => {
                return response.json();
            },(error) => {
                console.log(error);
                //your want to implement your own error handling here.
            });
    } 

And your component would look like

    ngOnInit(): void {        
         this.sellingMenuVarietiesService.getVarieties().subscribe((res) => {
             this.varietyListSelling = res;
         });
        console.log('initializing SellingMenuVarietiesComponent');
    }
like image 39
Sefa Avatar answered Nov 15 '22 05:11

Sefa