Steps for subscribing to a component variable in Angular 2

I've set up a header for my server URL in one of the components, and I want to use this header in all components whenever there is a server call. However, I am having trouble subscribing to this header. Can someone please assist me?

Interface component:

 import { Injectable } from '@angular/core';
 @Injectable()
export class Config {

 header = 'http://localhost/a2server/index.php/';

}

Main.ts (where I want to use the header):

 var data: any;
  constructor(public location: Location, public config: Config, public router: Router, public http: Http, fbld: FormBuilder, public toastr: ToastsManager) {

    this.config
        .subscribe(header => this.data = data); 
      console.log(this.data)

I realize I may be doing something wrong. Can someone please guide me?

Injectable:

import { Injectable } from '@angular/core';
  import { Http, Response } from '@angular/http';
  import { Observable } from 'rxjs/Observable';
  import { Component } from '@angular/core';
  import { IDetails } from './details';
 import { Config } from '../headers';
 @Component({
   providers: [Config]
})
@Injectable()
 export class GetCustInfo {
   header: any;
   str = localStorage.getItem('social');
   loc = JSON.parse(this.str);
   id = this.loc.profile_id;
    constructor(private _http: Http, public config: Config) {  this.header = this.config.header;}
 private _productUrl = this.header + 'profile/editcustominfo/' + this.id;
getCustList(): Observable<IDetails[]> {
    return this._http.get(this._productUrl)

.map((response: Response) => { 

    return <IDetails[]> response.json().data[0]; 

    });

}

}

Answer №1

If you want to work with observables, you can subscribe to them. When dealing with a simple string, all you need to do is access the property like this:

var data :any;
  constructor(public location: Location,public config:Config,public router: Router, public http: Http, fbld: FormBuilder,public toastr: ToastsManager) {

    console.log(this.config.header);

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

Encountering an issue with importing an enum: An error is triggered stating 'Variable implicitly has type 'any' in certain areas where its type remains undetermined.'

When I define simple enums in the same file, everything works fine. However, exporting/importing them causes numerous compilation errors related to types. It seems like the issue only arises when defining enums in a separate file, pointing towards a proble ...

Tips for converting NULL% to 0%

When running my calculatePercents() method, I am receiving NULL% instead of 0%. https://i.sstatic.net/NSbls.png Upon checking my console.log, I noticed that the values being printed are shown as NULL. https://i.sstatic.net/A7Jlk.png calculatePercents() ...

Bring in the module for DecompressionStream

I'm encountering an issue in my React Typescript app where I am seeing the following error message: webpack compiled with 1 warning ERROR in src/App.tsx:30:21 TS2304: Cannot find name 'DecompressionStream'. 28 | const enc = new TextEncod ...

What steps can I take to ensure Angular 8 is compatible with IE11?

After upgrading to Angular 8 with the ng update command, it initiated migration scripts that removed the es6/es7 imports from the polyfills.ts file. I had read that Angular would generate a special build for older browsers, such as IE11, eliminating the ne ...

Just getting started with Typescript and Angular and encountering issues with sending POST requests using Http

Recently, I started learning Angular and Typescript. One of the tasks I attempted was creating a basic login page. To achieve this, I developed a service in typescript that triggers upon clicking the 'Login' button. The input fields for username ...

Angular4 allows for the creation of a div that can horizontally scroll

Below is the HTML code I am working with: <div class="card-deck" fxLayout.xs="row" style="overflow: scroll; height:100%"> <md-card style="width:10rem" *ngFor="let make of filteredMakes" (click)="goToModels(make.niceName)" class=" ...

Error message: "Vue3 JSX files are throwing a ReferenceError because React is not defined."

Currently, I am working on integrating storybook with antdv. However, when importing a tsx file that contains jsx within the button.stories.js file, I encountered an error stating "ReferenceError: React is not defined". You can view the error here. It is i ...

Validation in Angular10 Reactive Forms can be triggered on blur and submit events

Seeking to validate the form both on blur and when the submit button is pressed, but facing a limitation with the options available: updateOn: ['blur', 'submit'] The current choices are either updateOn: 'blur' or updateOn: &a ...

Incorporate a generic type into a React Functional Component

I have developed the following component: import { FC } from "react"; export interface Option<T> { value: T; label: string; } interface TestComponentProps { name: string; options: Option<string>[]; value: string; onChang ...

VSC is throwing a type error, but is it still possible to compile the code?

It seems like after downloading some extensions, I started encountering this issue which was not present before. My files are now displaying errors even though everything should be fine. https://i.sstatic.net/cr7Ef.png The error seems to be related to ca ...

The function cannot be found within the specified file

Snippet.ts export class Snippet { public async processData(data): Promise<any> { //processing logic } } Snippet.spec.ts //correctly imported Snippet class describe('testing', async () =>{ it('ProcessData test ...

Angular allows for displaying objects within other objects using interpolation

Below is the object stored in EntryList variable within my component: { "id": 0, "startAddress": { "id": 6, "addressString": "addressString" }, "endAddress": { ...

Access the value of a BehaviorSubject within an Angular component

Seeking assistance with creating a comparison in my component where I want to display a message if successful, or redirect to another page after 3 seconds if not. However, I am unsure how to check for NULL with this *(this.link$.source.value.success) or (t ...

Issue "Module not found" arises while trying to import an external JSON file in TypeScript

Working with local JSON files is not an issue for me. I've successfully implemented the following code: import data from "./example.json"; However, I encounter an error when attempting to access remote files like the one below, resulting in a "Canno ...

Sequelize Error: Unable to access properties of an undefined object (reading 'replace')

An error occurred while attempting to create a new table. The specific error message is as follows: D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\utils.js:364 return s.replace(new RegExp(tickChar ...

Accessing a website with Angular 14 using a log-in feature and custom header

For the past week, I've been working on developing a service that can connect to a website and retrieve information from it, such as a list of machines. I want to achieve this using TypeScript with Angular and utilizing Angular's HTTP client. H ...

Angular 2: Finding the total of an item in ngFor loop

I need help with calculating the total amount of items outside of an ngFor loop. HTML <div *ngFor="let item of items"> <input type="text" [(ngModel)]="item.price"> <input type="text" [(ngModel)]="item.quantity" (ngModelChange)=" ...

An error was encountered at line 7800, character 18 in the three-core.d.ts file in the node_modules/@types/three directory. The error message reads: "Cannot find name 'VRDisplay

I encountered an error in my Angular 6 app while running ng serve ERROR in node_modules/@types/three/three-core.d.ts(7800,18): error TS2304: Cannot find name 'VRDisplay'. node_modules/@types/three/three-core.d.ts(7801,23): error TS2304: Canno ...

Exploring the use of .pipe with Angular Jest for testing

Currently, I am trying to test the following .ts file: create(entityResourceID, params: any): Observable <any>{ const url = `${this.apiUrl}/${entityResourceID}/assignee`; return this.http.post(url, params).pipe( map(() ...

The resolution of Ionic 2 / Angular 2 providers is causing difficulty

Having issues with providers and injections in Ionic 2 since version 2.0.0. Encountering the following error (with various providers, not just this one): Uncaught Error: Can't resolve all parameters for LoginRedirectService: (App, ?, AlertContro ...