Data from the server isn't loading in Angular2

I have successfully developed a basic Java app using REST that returns a string value when accessed through a REST client. However, I am now facing an issue in fetching the string value using an Http REST client in Angular2. I have set up a service to retrieve data from the REST client in Angular2 which indicates successful access to the REST client. But when I try to display the retrieved data like {{serverData}}, it does not show anything.

service.ts

@Injectable()
export class HttpSiftgridService {
private url:string = "http://localhost:8080/app-rest/rest /getData";
constructor(private _http: Http) {}
getSiftgridData() {
    alert(this._http.get(this.url).map(res => res.json));
    alert("hh");
    return this._http.get(this.url).map(res => res.json);
}
private handleError(error : Response) {
    console.error(error);
    return Observable.throw(error.json().error || ' error');
}

}

app.component.ts

export class AppComponent implements OnInit{ 
serverData: string;
constructor(private _httpService:HttpSiftgridService) {}
ngOnInit() {
    this._httpService.getSiftgridData()
        .subscribe(
          data => this.serverData = JSON.stringify(data),
          error => console.log("Error in getting Data"),
          () => console.log("Successfully")
    );
}

}

My REST application is running on Tomcat server.

Answer №1

Modification:

update the code snippet from
return this._http.get(this.url).map(res => res.json);

To:

return this._http.get(this.url).map(res => res.json());

Answer №2

Although this may not be the conventional solution, it cannot be utilized as a comment:

By making the following adjustment

ngOnInit() {
    this._httpService.getSiftgridData()
        .subscribe(
          data => {
            this.serverData = JSON.stringify(data);
            console.log(data);
          },
          error => console.log("Error in getting Data"),
          () => console.log("Successfully")
    );
}

Will the data be displayed?
Will Successfully be shown?

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

incorrect indexing in ordered list

I am facing an issue with the ngIf directive in Angular. My objective is to create a notification system that alerts users about any missing fields. Here's a stackblitz example showcasing the problem: https://stackblitz.com/edit/angular-behnqj To re ...

Begin by executing the angular repository on your local machine

Is it possible to run the Angular repository found on GitHub at github.com/angular/angular locally through localhost? The README for the repository does not offer any guidance on running it locally. Running 'yarn' will build the site, but how do ...

Problem with Angular 5: Data Binding Issue未知EncodingException

Struggling to understand... I want to make a GET request to my service to retrieve the specific hardware associated with the barcode I scanned - this part is working correctly. The hardware information is returned as an object that looks like this -> How ...

Ionic Troubleshoot: Issue with Reading Property

Encountering an error: A TypeError occurs: Cannot Read Property of "username" of Undefined The HTML code responsible for the error is as follows: <ion-content padding style="text-align: center; margin-top: 35px"> <form (ngSubmit)="logFor ...

Step-by-step guide on how to index timestamp type using Knex.js

I'm in the process of indexing the created_at and updated_at columns using knex js. However, when I try to use the index() function, I encounter the following error: Property 'index' does not exist on type 'void' await knex.sche ...

Converting Axios URL Parameter to Array of Strings in ExpressJS

How to Send a GET Request using axios: await this.client.get('/endpoint', { params: { query: ['max', 'kevin'] } }) This will result in a URL that looks like this: Request GET /endpoint?query[]=max&query[]=kevin Any sugge ...

Attempting to transfer a username String from the client to the server using React and Typescript

I am working on a project where I need to send the username of a logged-in user from the Client to the Server as a string. Currently, I am able to successfully send an image file, but now I also need to send a string along with it. What I aim to do is repl ...

Using cucumber to perform login procedures across various scenarios

Currently, I am utilizing Selenium with Cucumber (using Java, although it's not entirely relevant). Suppose I have the following scenarios: Feature: Example Feature Scenario: Perform action A on website Given the website is open And user ente ...

Disappearing White spaces in a Java Swing Label with HTML TagsIn a Java

I'm facing an issue where coloring one character in a string causes most of the whitespaces to disappear. I'm puzzled as to why this is happening and if there's a viable solution? map[9] = "# # ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Dividing a TypeScript NPM package into separate files while keeping internal components secure

I have developed an NPM package using TypeScript specifically for Node.js applications. The challenge I am facing is that my classes contain internal methods that should not be accessible outside of the package, yet I can't mark them as private since ...

Capture and handle JavaScript errors within iframes specified with the srcDoc attribute

My current project involves creating a React component that can render any HTML/JavaScript content within an iframe using the srcDoc attribute. The challenge I am facing is implementing an error handling system to display a message instead of the iframe ...

Angular allows you to pass an array of objects as FormData items

Is there a way to send FormData with an array of objects to an API? I have attempted the following: https://i.stack.imgur.com/BlYby.png This is the request payload. How can I retrieve all items with other data from my .NET Core C# API? public class Back ...

Encountered issue: The type 'Teacher[]' cannot be assigned to the type 'Teacher'

I am currently working on enhancing my angular application by adding a new service. However, I have encountered an error that I need help fixing: The error message states: Type 'Teacher[]' is not assignable to type 'Teacher'. Property ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

Use Jackson to convert JSON into a Java object that includes a collection

Exploring the capabilities of Jackson, I've set up a basic test scenario. In this case, I have a class with an object that serves as a parameter and return value for a Jersey method. Below is the structure of the class: import java.util.List; public ...

What is the best way to activate an <ion-datetime> with an <ion-button>?

Im currently attempting to execute the following action: I would like to select only the month and year using the example below: <ion-datetime presentation="month-year"></ion-datetime> However, I do not wish for this label to be vis ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

Is it possible for me to employ T extends Contravariant<any> to effectively restrict a generic type to a union of Contravariants

Let's begin by clarifying some terms: type Contravariant<T> = (t: T) => void; declare let cNum: Contravariant<number>; declare let cStr: Contravariant<string>; Now, suppose I wish to create a function that accepts an array of the ...