Encountering a "subscribe is not a function" error while attempting to utilize a JSON file in Angular 2

My attempt to import a JSON file into my service is resulting in the following error:

Error: Uncaught (in promise): TypeError: this._qs.getBasicInfo(...).subscribe is not a function(…)

The current state of my service file is as follows

@Injectable()

export class QuestionService {

BasicInfoData: Observable<any>;

constructor(private http: Http){}

getBasicInfo() {
    this.BasicInfoData = this.http.get('app/questionnaire/questions.json').map(res =>
    res.json()).subscribe(data => this.BasicInfoData = data ) as Observable<any>

    return this.BasicInfoData;
    }

}

and this is how my component is structured

@Component({

    moduleId    : module.id,
    selector    : 'questionnaire-page',
    templateUrl : './questionnaire.component.html',
    providers   : [ QuestionService ]
})

export class QuestionnairePage implements OnInit, OnChanges {

    BasicInfo: Observable<any>;

    constructor(private _qs: QuestionService, private fbuild: FormBuilder) {}

    ngOnInit() {
        this._qs.getBasicInfo().subscribe( data => this.BasicInfo = data );
     console.log(this.BasicInfo);
    }

}

Prior to attempting to call the data from my service, I had no issues calling it directly within the ngOnInit() of my component, like so

this.http.get('app/questionnaire/questions.json').subscribe(res => {
     this.Questions = res.json()
     console.log(this.Questions);
});

I initially tried the same approach and upon further research, incorporated the use of Observable. After reading about RXJS, I discovered that directly subscribing to the data causing issues. The solution suggested utilizing .map() first before subscribing. Despite making these adjustments, I continue encountering errors. I have attempted various solutions but either encounter an error earlier in the code or face the same issue repeatedly. Any insights on why this problem persists?

Answer №1

This particular piece of code is designed to fetch a Subscription

retrieveBasicData() {
    this.basicInformation = this.http.get('app/questionnaire/questions.json').map(response =>
    response.json()).subscribe(data => this.BasicInfoValue = data ) as Observable<any>

    return this.basicInformation;
    }
}

subscribe is actually a method belonging to the Observable class, and not the Subscription class. You are most likely interested in achieving something like this:

retrieveBasicData() {
    return this.http.get('app/questionnaire/questions.json')
    .map(response => response.json());
}

By implementing it this way, you will obtain an Observable that can be subscribed to.

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

The Ionic and Angular application solely displays dynamic HTML with no encapsulation using ViewEncapsulation.None

I'm struggling to grasp the concept of encapsulation: ViewEncapsulation.None within the @Component. @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], encapsulation: ...

Guide on customizing a dropdown button in a class-based Angular library with version 4 or higher

My dilemma revolves around utilizing the Angular Material library for a drop-down navigation bar. The issue at hand is my desire to hover through the list, yet I am unable to tweak the style within HTML. Fortunately, I can easily make alterations in Chrome ...

The variable 'module' is required to be of type 'any', but it is currently identified as type 'NodeModule'

I am currently working on a project using Angular and have just installed version 1.0.5 of ng2-dropdown-treeview. After installation, I restarted my server by running npm start. Upon checking the server log, I encountered the following error message: [PA ...

Exploring subobjects while fetching observables (typescript/angular)

When retrieving JSON from an API into an Angular service, I am working with a collection of objects structured like this: { "data": { "id": 1, "title": "one" }, "stats" : { "voteCount": 8 } } I am particularly interested in the ' ...

Is there a way to view Deno's transpiled JavaScript code while coding in TypeScript?

As I dive into Typescript with Deno, I am curious about how to view the JavaScript result. Are there any command line options that I may have overlooked in the documentation? P.S. I understand that Deno does not require a compilation step, but ultimately ...

Issues arise in Ionic 3 when attempting to use scripts or external custom jQuery plugins within inner pages

When I utilize a script tag in my index.HTML file, it functions properly on the initial or root pages of Ionic 3. However, upon navigating to other pages using NavController, the script ceases to work on these inner pages. How can I implement a custom jQ ...

Sharing content on an Angular 4/5 webpage

I find myself in a situation where I am required to share a link to my web application with a client, and they will be submitting a form on my webpage. This application has been developed using Angular 5. Despite searching online for a solution, I have not ...

Instructions for adding a prefix of +6 in the input field when the user clicks on the text box

Recently, I've been utilizing Angular Material elements for input fields which can be found at this link. An interesting feature that I would like to implement is automatically adding '+6' when a user clicks on the phone number field. You ...

What is the best method to remove a value from a JSON object in a CSV file?

I received a JSON response like this: xxx: ["fsd,das"] I am looking for a way to remove the value "fsd" from the JSON object. The issue is that the response inside the JSON is not actually an array, but rather a CSV format. How can I go about deleting it ...

Error code 2532 occurs when trying to access an object using square brackets in TypeScript

Encountered the ts error: Object is possibly 'undefined'.(2532) issue while trying to access the value of a field within an object, where the object key corresponds to a value in an Enum. Below is a concise example to showcase this problem: en ...

Limit function parameter types to object keys

Is it possible to constrain my function parameter to match the keys of an object? I want to achieve something similar to this: export const details = { x: { INFO_x: 'xxx' }, y: { I ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

Guide to implementing an "export default" with various types and values in a TypeScript module

There is a simple way to export multiple values as default: class Car {...} class Bus {...} export default { Car, Bus } You can also easily export a type as default export default interface Airplane {...} However, exporting multiple types as default i ...

Guide on connecting ngrx/store to an angular router guard

As someone who is new to ngrx/store, I am embarking on my initial project utilizing this tool. After successfully setting up my angular project with ngrx/store, I discovered how to dispatch a load action following the initialization of my main component: ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...

Unable to fulfill the return type requirement in a typed TypeScript function

In this scenario, let's consider the following type: export type Transformer = <T extends any[], U>( data: T, ) => U; Now, let's examine a function that needs to adhere to this type: export const transform: Transformer = ( d ...

"Utilizing FormData in an IONIC 5 project with

While creating a user profile, I am encountering an issue where the FormData being generated for sending is empty despite all other fields having values. Below is the code snippet from cadastro.ts: import { Component, OnInit } from '@angular/core&ap ...

What is the best way to increase the size of an array and populate it with just one specific element in Types

If I want to create an array in Python, like [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], all I have to do is use [1] * 10. >>> [1] * 10 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] Is it possible to achieve the same result in TypeScript? ...

What is the best way to conduct tests on Typescript modules that are not intended for

Even though the compiler accepts my current solution without any errors, the tests are still failing with the message "ReferenceError: myFunction is not defined". I am interested in testing the functionality of the following module using TypeScript: File1 ...

Is it impossible to use type as a generic in TypeScript?

Struggling with TypeScript in React and encountered an issue. I decided to use a generic to build an abstracted class related to Axios. However, I ran into an ESLint error when using any as the type parameter for my generic. ESLint: Unexpected any. Specif ...