What is causing Angular 6 to fail in sending HTTP Get/Post requests?

In Angular 6, I have created a LoginService like this:

@Injectable()
export class LoginService {
    constructor(private http: HttpClient) { }

    login(): Observable<boolean> {
        var url = `${environment.baseAPIUrl}${environment.loginUrl}`;

        return this.http.get<boolean>(url);
    }
}

Now, I am calling this service from my LoginComponent:

@Component({
    selector: 'bpms-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

    constructor(private loginService: LoginService) { }

    ngOnInit() {
    }

    login() {
        var self = this;
        self.loginService.login();
    }
}

I am facing an issue where my request is not being sent. Any idea why?

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

Answer №1

Observable is only triggered when a subscription is made to it. The Http API method returns an Observable, simply creating the observable does not initiate an API request.

self.loginService.login().subscribe(
  (data) => console.log('Successfully logged in')
);

Answer №2

Http Requests are only initiated once the observable is subscribed to.

@Component({
selector: 'bpms-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

constructor(private loginService: LoginService) { }

ngOnInit() {
}

login() {
    var self = this;
    self.loginService.login().subscribe();
 }
}

Answer №3

Make sure to execute your login function by calling it, such as in the ngOnInit() method or on form submission events.

Additionally, be sure to update your login function to resemble the following code:

login() {
    this.loginService.login()
        .subscribe((res) => console.log('response from login() function'));
}

Answer №4

In the case where your return type is Observable<, it is necessary to subscribe to it in order to receive a response once it becomes available. This means that your code will resemble something like the following:

@Component({
selector: 'bpms-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

constructor(private loginService: LoginService) { }

ngOnInit() {
}

login() {
    var self = this;
    self.loginService.login().subscribe();
 }
}

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

Identify the appearance of a web component being added to the Document Object

After reading this discussion regarding a web-component I created: <my-vue-web-comp [userId]="1" id="my-component"></my-vue-web-comp> The component functions properly in Angular. How can I determine when the web component h ...

In Typescript, encountering a member of a union type with an incompatible signature while utilizing the find method on an array of

I need to verify if a specific value exists within an array of objects. The structure of my array is as follows: [ 0: { id: 'unique_obj_id', item: { id: 'unique_item_id', ... }, ... }, 1: {...} ] The objects in the ar ...

"Classes can be successfully imported in a console environment, however, they encounter issues when

Running main.js in the console using node works perfectly fine for me. However, when I attempt to run it through a browser by implementing an HTML file, I do not see anything printed to the console. Interestingly, if I remove any mentions of Vector.ts fro ...

How to conditionally apply a directive to the same tag in Angular 4

I am implementing angular 4 and have a directive in my template for validation purposes. However, I would like to first check if a specific condition is true before applying the directive. Currently, my code looks like this: <div *ngIf="groupCheck; els ...

Executing npm prepublish on a complete project

I am facing a situation with some unconventional "local" npm modules that are written in TypeScript and have interdependencies like this: A -> B, C B -> C C -> D When I run npm install, it is crucial for all TypeScript compilation to happen in t ...

Guide on how to utilize Protractor for end-to-end testing to access the scroll bar within the div

I am currently working on an end-to-end script, but I am running into trouble accessing an element when a div overflows and the scrollbar within the div is activated. Specifically, within the form, I need to access the scroll down feature inside the div o ...

What are some ways I can incorporate fragments into my apollo-angular workflow?

Currently, I am using Angular 13 along with apollo-angular 3.0.0 and have implemented the GraphQL query codes as follows: const GET_TODOS = gql` query GetTodos() { todos() { id title brief body tags created_at ...

What is the best way to invoke a function from a Service to a Component in Angular?

Currently, I am in the process of learning Angular and recently created an alarm clock feature. In this functionality, users have the option to select alarms they wish to cancel by using checkboxes that are then stored in local storage through the use of & ...

Is there a way to convert a File into a byte array and then save it in a database using Angular and ASP.Net Core?

Hey everyone, I'm fairly new to working with Angular and I've hit a roadblock when trying to implement file-upload functionality in my Angular application. The technologies I am using include Angular, ASP.Net Core, and Sqlserver. I am tasked wi ...

How can I trim a value using one-way data binding in Angular?

Is there a way to trim values in Angular using one-way data binding? Can this be done directly in the component.html file rather than in typescript? I tried the following but it didn't work: <P>{{country.trim()}}</P> Thanks ...

Developing a Library for Managing APIs in TypeScript

I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that cal ...

What is the best way to integrate Angular material into a Bazel-enabled project for a custom library development?

Is there a way to incorporate Angular material into a project enabled with Bazel in a custom library? Check out the code I am using: https://github.com/AkshayC1736/angular-bazel.git ...

Maintain the spacing of an element when utilizing *ngFor

Using Angular.js and *ngFor to loop over an array and display the values. The goal is to preserve the spaces of elements in the array: string arr1 = [" Welcome Angular ", "Line1", "Line2", " Done "] The ...

Error encountered when attempting to implement Material Angular 2 autocomplete functionality

I encountered an issue with Angular 2 while integrating autocomplete in material design. This is my first attempt at implementing it along with practicing backend ASP.net Core. Despite trying to install some ng2 libraries, I still couldn't get it to w ...

Uploading files using Remix.run: Transforming a File object into a string during the action

I'm currently developing a Remix application that allows users to upload files through a form. I have a handler function for handling the form submission, which takes all the form data, including file attachments, and sends it to my action. The probl ...

Retrieve the md-sidenav-layout element within a TypeScript file component

Using md-sidenav in my application has been quite useful. Assigning an object to md-sidenav involves the following syntax: <md-sidenav #start With this syntax, "start" will hold all variables and methods of md-sidenav, allowing for operations such ...

Encountered an error while trying to run the command "lite-server" in Angular 2

I recently had a machine where I installed Zsh and OhMyZsh, but later on uninstalled them. However, now whenever I try to run "npm start" on the Angular 2 Quick Starter template, I keep encountering this error message: Error occurred when executing comma ...

Having difficulty resolving the fs and child_process modules

Even though I've come across numerous questions with similar situations, none of them have provided the solution I need. I'm attempting to utilize the 'ffmpeg-static-electron' dependency on Angular Electron. After running npm install ...

Step-by-step guide: Mocking a fetch request in Jest using React with TypeScript

In my project, I am developing a react+ts application which allows users to search for other users using the GitHub API. The search input element in my app has the following structure : <input type="text" placeholder="Search us ...

Using FIND to search an array object results in an error: Type 'undefined' is not compatible with type ''

I'm currently attempting to search for an element within one array and then assign it to another array object. However, I keep receiving the following error message: Type 'ClosureSummary | undefined' is not assignable to type 'Closure ...