Instructions on how to sign up for a worldwide technique that is known as

I have a file called globalvars.ts where I added a global method. How can I subscribe to this method in the ts page where it is being called?

globalvars.ts;

httpgetmethod(url:string)
{
  var veri;   
  var headers = new Headers();
  headers.append('Accept', 'application/json');
  headers.append('Content-Type', 'application/json' );
  headers.append('Authorization' , 'Bearer '+ "");
  let options = new RequestOptions({ headers: headers });

  this.http.get(url, options)
  .subscribe(data => {
    console.log( data['_body']);
    veri=data['_body'];
    veri = veri.replace(/\\/g, "");
    veri = JSON.parse(veri);
    return veri;

  });

profile.ts;

globalvars.httpgetmethod("").subscribe;

I want to invoke the subscription here.

Thanks.

Answer №1

If you're looking for a service in Angular, here's an example of a simple Angular Service:

import { Injectable } from '@angular/core';

import { Hero } from './hero';
import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService {
  getHeroes(): Hero[] {
    return HEROES;
  }
}

To use this service in your app, include it like this:

@NgModule({
  //other metadata properties
  providers: [HeroService]
})

And in your component, you can utilize the service like this:

constructor(private heroService: HeroService) { }

For more information on services in Angular, check out this tutorial and this resource.

UPDATE

Service Example:

getUser(user:string){
    return this.client.get('https://api.github.com/users/'+user);
  }

Component Example:

 constructor(
private service: AngularService) {

    this.weatherService.getUser(term)
      .subscribe((result) => {
        console.log(result);
        this.result = result;
      });

  }

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 steps can I take to avoid encountering the `@typescript-eslint/unbound-method` error while utilizing the `useFormikContent()` function?

Recently, I updated some of the @typescript-eslint modules to their latest versions: "@typescript-eslint/eslint-plugin": "3.4.0", "@typescript-eslint/parser": "3.4.0", After the update, I started encountering the fo ...

What is the best way to maintain the routerLinkActive state when navigating to another component page that is related to the current page

Why does the navigation link become inactive when routing from myloans to syncmyloans? How can I maintain navigation activation when moving to related sub pages within the main navigation? Navigation <nav> <ul class="navbar-nav ml-auto&q ...

Tips for ensuring elements within a modal receive immediate focus when opened in Angular 2

I am relatively new to Angular JS and I am encountering some challenges with implementing a directive in Angular 2 that can manage focusing on the modal when it is opened by clicking a button. There have been similar queries in the past, with solutions pr ...

How can I ensure I am receiving real-time updates from a Resolver Service by subscribing and staying in sync with the

How can I effectively implement this code without encountering an error? "Property 'resolve' in type 'DocumentaryResolverService' is not assignable to the same property in base type 'Resolve'." import { Documentary } from ...

Top method for managing dates in TypeScript interfaces received from the server

After encountering the issue detailed in Dates in a Typescript interface are actually strings when inspected I faced a challenge while defining a TypeScript interface for a response from a server API, particularly with a Date parameter. The data arrived a ...

Guide on implementing the Translate service pipe in Angular 2 code

So here's the issue... I've integrated an Angular 4 template into my application which includes a functioning translate service. The only problem is, I'm unsure of how to utilize that pipe in my code. In HTML, it's as simple as adding ...

The element you are trying to access, "noUiSlider," does not belong to the type "HTMLElement" and cannot be found

Running into a roadblock here. What mistake am I making? .... /// <reference path="../../../typings/tsd.d.ts" /> var slider:HTMLElement = document.getElementById('slider'); noUiSlider.create(slider, { start: +$input.val(), step: + ...

Inject data into an Angular 2 template

Does anybody know of a method to pass variables to templates in Angular2? Suppose I have the following code snippet: <div *ngFor="foo in foos"> <ng-container *ngTemplateOutlet="inner"</ng-container> </div> --------------- <n ...

<Click here to navigate to page 2> await whenClicked={navigation.navigate("page_2")} />

Issue with assigning a 'string' to a parameter in TypeScript while trying to navigate to another screen in React Native. Can anyone help with this error? This problem occurs when we want to navigate to another screen using TypeScript in React Na ...

Access to Angular 7 granted through Gmail authentication

I am currently attempting to authorize Gmail in Angular 7 using Angular5-social-login. While it is working for me, I need the function to run on page load. I have tried calling it in ngOnInit and ngAfterViewInit but encountered the following error: Un ...

Following the update to Angular 6, an error was encountered: CssSyntaxError:

Currently, I am in the process of upgrading my Angular 5 application to Angular 6. Following all the necessary steps outlined on update.angular.io, I have encountered a compilation error that persists even after completion of the upgrade process. The err ...

Access my web application to easily download Jira tickets in XML format with just a single click

In order to retrieve all tickets from Jira within a specific time period, I currently have to manually extract them by clicking on the extract button in XML format. Subsequently, I download this XML file onto my web application and save it into the databa ...

Leveraging *ngFor to extract HTML content from ion-label

I've encountered an issue while using *ngFor in my HTML like this: <ion-slides #slides [options]="slideOpts"> <ion-slide class="numbers-wrapper" *ngFor="let questionNumber of numbers" (click)="clickQue ...

Is there a source where I can locate type definitions for Promise objects?

In the process of creating a straightforward class called Primrose, I am extending the global Promise object in order to include additional methods like resolve and reject. export class Primrose<Resolution> extends Promise<Resolution>{ priv ...

Tips for adding a border to a table cell without disrupting the overall structure of the table

Looking for a way to dynamically apply borders to cells in my ng table without messing up the alignment. I've tried adjusting cell width, but what I really want is to keep the cells' sizes intact while adding an inner border. Here's the sim ...

What is the best way to convert dates in Angular's DatePipe using moment.js?

My current package versions are as follows: "@angular/cdk": "^11.2.13", "@ngx-translate/core": "^13.0.0", "@angular/material-moment-adapter": "^12.2.9", "moment": "^2.29.1", &q ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

Can someone explain how to define "a type of object that must not be empty" in typescript?

I'm working with a function that can operate on any type T, but with the constraint that if T is an object, it cannot potentially be empty. Here's what I've tried: declare function myFunction<T>(param: T extends Record<string, neve ...

Determine the dynamic height of content in a TypeScript file

Could you please provide guidance on obtaining the height of the content within this particular div element? For example, I need to calculate the dynamic height of the content. code .html <div class="margin-top-47 margin-horizontal-10" #hel ...

Initially, when an iframe is loaded in Angular 10, it may display a 404 error page

Hey there! I'm currently using the HTML code below to incorporate an iframe and display an external page hosted on the same domain so no need to worry about cross domain issues: <iframe frameborder="0" [src]="url"></iframe ...