What could be causing the availability of a response in a service, but showing as undefined in the component?

Currently, I am facing a problem with my service and component setup. While the service can successfully read the response as a JSON object, the component is returning res: undefined.

service:

constructor(
    private http: Http,
    private fbuilder: FormBuilder,
    private user: UserService
) {}
login(uname:string, pass:string): Observable<any> {

    let headers = new Headers({
        'Content-Type': 'application/json',
        'Username':uname,
        'Password':pass
    });
    let options = new RequestOptions({ headers: headers });
    let data = {};
    var Observable = this.http.post( url, data, options )
    .map(res => {
        res.json();
    })
    .catch( (error: any) => Observable.throw(error.json().error || 'Server error') );
    return Observable;
}

component:

constructor(
    private http: Http,
    private fbuilder: FormBuilder,
    private user: UserService
) {}
loginUser(uname: string, pass: string) {
    this.user.login(uname, pass).subscribe(
        res => {
            console.log('res: ' + JSON.stringify(res));
        },
        err => {
            this.errorMessage = err;
        }
    );
}

Answer №1

Seems like the issue lies within this block of code:

.map(res => {
    res.json();
})

The problem is that you're not returning the result from res.json. To fix this, simply add the return statement as shown below:

.map(res => {
    return res.json();
})

Alternatively, you can simplify it by removing the curly braces, like this:

.map(res => res.json())

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

Utilizing jq to iterate through JSON and perform replacements

UPDATE: After reassessing my initial question, I have found that I can extract all the necessary data in one API call. The JSON response from my API call is as follows: { "lights": { "8": { "name": &qu ...

Node.js causing issues with retrieving data from REST Calls

I am trying to make a REST API call from my PHP and Node.js application to a specific URL provided by the client, which is expected to return a JSON object. While I am able to successfully retrieve data using PHP, I'm encountering issues with my Node ...

Unable to make custom font work in TailwindCSS and ReactJS project

I have incorporated a custom font into my projects using React, TypeScript, TailWind, and NextJS. The font file is stored in the /fonts directory with the name Glimer-Regular.ttf. To implement the font, I added the following code snippet to my global.css ...

"Experiencing issues with Mongoimport when using JSON files - the provided JSON file seems

My attempt to import JSON data into MongoDB via a JSON file using the command below is resulting in an error: mongoimport --db my_db --collection m_data --type json --file /home/uname/email_my.json -v One of my key values contains a complete HTML with sp ...

How can one pass a generic tuple as an argument and then return a generic that holds the specific types within the tuple?

With typescript 4 now released, I was hoping things would be easier but I still haven't figured out how to achieve this. My goal is to create a function that accepts a tuple containing a specific Generic and returns a Generic containing the values. i ...

The function 'ChartModule' cannot be called, as function calls are not supported

I am encountering a similar problem as discussed in Angular 2 - AOT - Calling function 'ChartModule', function calls not supported ERROR: Error encountered while resolving symbol values statically. Trying to call function 'ChartModule&apos ...

What is the process for choosing nested colors from a theme in Material UI?

I have a question regarding how to select a nested style from my theme when creating a Button. Below is the snippet of code that illustrates my dilemma: const buttonStyle: SxProps<Theme> = { '&:hover': { backgroundColor: 'bac ...

how to use all parameters except the first one in TypeScript

Is there a way to reference one function's parameter types in another function, but only use a subset of them without repeating the entire list of parameters? //params of bar should be same as foo, except p1 should be a different type function foo(p1 ...

The parameter cannot be assigned to type 'void' because it is of type 'Promise<unknown>'.ts(2345) - mockReturnValueOnce

Encountering an error while using the mockReturnValueOnce method, specifically 'Argument of type 'Promise' is not assignable to parameter of type 'void'.ts(2345)'. I attempted to solve it by writing the following code: .spyO ...

Is there a way to ensure that fields in a sub component are validated whenever we attempt to switch the Tab using a route

Hi there, I could really use your assistance. I've done some research, but I haven't been able to find a suitable solution for my problem. I have this shared component that contains the following code which enables tab navigation through various ...

Creating a custom validation for browsing HTML files in Angular using the Form Builder

Currently, I am using reactive form validation to validate a file upload control. I have implemented a change directive to manage its validation. <label class="btn btn-primary btn-file"> Browse <input type="file" (change)="fileChanged($event)" ...

Why can't I omit <someUnion, oneInterface> in TypeScript?

Kindly review this simple example: interface A { a: number; } interface B { b: number; } interface C { c: number; } type ABC = A | B | C; type omitA = Omit<ABC, A>; https://i.sstatic.net/5Mun4.png Unfortunately, I am unable to exclude an i ...

"Using Node.js createReadStream, only a single data chunk from a large JSON file is read at

I am currently utilizing Nodejs to extract JSON objects from an extensive JSON file (1GB+). The JSON data is structured as [{field1: x, field2: x, field3: x},{...},...,{...}], without any delineation between each object. To prevent memory issues, I have im ...

Error: The function child.send is not defined as a valid function

Encountering an issue while attempting to build my Angular application. npm run build All tasks run smoothly on local machine and the project is successfully built. However, when trying to execute the command on the server via console (ssh), I am faced w ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

Troubleshooting Issue with Angular Property Binding for Image Dimensions

Currently, I am exploring property binding in Angular through an example. The idea is to use an image and bind its width, height, and src attributes using property binding. Surprisingly, even though there are no errors and the image renders successfully vi ...

How to link Array with Observable in Angular2 Typescript without using .interval()

Is it possible to achieve the same functionality without using the "interval()" method? I would like to link an array to an observable, and update the array as well as have the observable monitor the changes. If this approach is feasible, how can we inco ...

Transform an HTML table string into JSON format

I discovered a useful library called table to JSON that allows me to convert an HTML Table to JSON using its ID (#testtable in the example below): var table = $('#testtable').tableToJSON(); alert(JSON.stringify(table)); However, I am interested ...

Leverage advanced type deduction in Key Remapping

I'm puzzled by this code snippet: type Foo<T extends string> = [T] extends [infer Y] ? Y : never // works fine type Test_2<T extends Array<string>> = { [P in T[number] as Foo<"foo">]: undefined } // no issues type ...

All-encompassing NextJS App router with a focus on Internationalization

I am currently working with a folder structure that includes an optional catch-all feature. The issue I am facing is that the page does not change when the URL is altered to include ""/"" or ""/about-us"". It consistently remains on the ...