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

Unable to utilize ngForm when values are already predefined

I have an Angular application with Ionic 4. Here is the HTML code for my form: <form #formAuth="ngForm" (ngSubmit)="sendCode(formAuth)" method="post"> <ion-select placeholder="Country" ngModel name="area_code" interface="modal"> <io ...

A guide to resolving the error "Cannot read properties of undefined (reading 'length')" while implementing pagination with react, Material-UI, and TypeScript

As I work on my code, my goal is to display a limited number of cards per page based on the data stored in a JSON file. I anticipated that clicking on the ">" or "<" icon would navigate to the next or previous page respectively, updating the displayed card ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

Discovering the generic parameter in the return type using TypeScript

I am struggling with a specific issue export type AppThunk<ReturnType> = ThunkAction< ReturnType, RootState, unknown, Action<string> >; After implementing the above code snippet export const loadCourse = (id: string): AppThunk ...

Guide on specifying the return type of a generic class when using TypeScript

The code I am working with is structured like this: import * as events from 'events' // Utilizing Node.js events module // My custom implementation of EventEmitter with enhanced typing interface IEventEmitter<EventTypes> { /* ... */ } // ...

Transfer my testing utilities from React Router version 5 to version 6

I am currently transitioning my project to React V6 router and encountering an issue with my test utility function. Every time I run the test, all my expectations fail because jest cannot locate the object. Has anyone faced this error during a similar migr ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

Establishing an efficient development environment with continuous integration for react-native using typescript and nodejs

Unfortunately, we encounter the challenge of working with different nodejs versions in our projects. I am unsure if this is similar to Java where multiple jdks can be installed (multiple nodejs installations), and each project automatically utilizes the co ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

What is GraphQl indicating when it informs me that I neglected to send arguments for the mutation

My GraphQL schema consists of various mutations and queries. I believe that validation of mutations should only occur when I send mutation { ... } to the graphql server. However, currently, the server is informing me that I have not sent arguments for all ...

Resetting the Angular2 poller in an ng-bootstrap accordion

I am currently utilizing a multi-dimensional array connected to a reactive poller that waits for a database state update. Interestingly, when I initially load the state once, the user interface functions as intended. However, a challenge arises when I act ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

Checkbox selections persist when navigating between pages

I am currently working with Angular 9 and I have a list of checkboxes that need to default to true when displaying certain data. If one of these checkboxes is unchecked, it should trigger the display of specific information. The issue I am facing is that o ...

Could you tell me the kind of theme used in Material-UI version 5?

I've decided to switch my project over to MUI version 5 and embrace the use of emotion CSS. It's come to my attention that I need to incorporate the theme property, but now TypeScript is prompting me for a type definition for it. The current code ...

How to efficiently retrieve parent content from a child component

parent.html <ion-content class="project"> <ion-grid> <ion-row class="details"> <project [data]="data"></project>// this child component </ion-row> </ion-grid> </ion-content> project.ht ...

Can you provide instructions on how to use RXJS Observables to conduct a service poll?

If I want the get request to "api/foobar" to repeat every 500 milliseconds, how can I modify the code provided below? import {Observable} from "RxJS/Rx"; import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; @Injectable() export ...

Choose an option from a selection and showcase it

I need to implement a modal that displays a list of different sounds for the user to choose from. Once they select a sound, it should be displayed on the main page. Here is the code snippet for the modal page: <ion-content text-center> <ion-ca ...

Show a specific form field based on the chosen option in a dropdown menu using Angular and TypeScript

I am looking to dynamically display a form field based on the selected value from a dropdown list. For instance, if 'first' is chosen in the dropdown list, I want the form to remain unchanged. However, if 'two' is selected in the drop ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

Learn the process of generating an ID and dynamically updating its content using Angular

I have a coding challenge where I need to dynamically create an ID and retrieve it in order to change its content upon clicking. Here is the code snippet: <div class="row" *ngFor="let row of [1, 2, 3]"> <button (click)=&quo ...