Tips for sending parameters in a function call within Angular 6

Welcome to freeapiservice, my unique web service where I aim to invoke a function from another class named app.component within the insertFormadata function. The goal is to call a parameter from the same app.component:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpParams } from '@angular/common/http';

@Injectable()
export class freeApiService {
    constructor(private httpclient: HttpClient) {
    }

    insertFormadata(): Observable<any> {
        return this.httpclient.get("/api/api?type=savedata&fname=nilesh&tfvalue=js&mobile=6547896541&type_sec=1452&city=bhopal&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0959d91999ccd9e9b918294918495b0979d91999cde939f9d">[email protected]</a>")
    }

    getcomments(): Observable<any> {
        return this.httpclient.get("http://jsonplaceholder.typicode.com/posts/1/comments")
    }

    getcommentsbyparameters(): Observable<any> {
        let params1 = new HttpParams().set("userId", "1");
        return this.httpclient.get("http://jsonplaceholder.typicode.com/posts", { params: params1 })
    }
}

In the app.component.ts file, when the onSubmit button is clicked, I have included JSON.stringify(this.data.name). This value needs to be passed to the webservice API.

import { Component } from '@angular/core';
import { freeApiService } from './services/freeapi.service';
import { Comments } from './classes/comments';
import { from } from 'rxjs';
import { Posts } from './classes/posts';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'applykaroo';
    data: any = {};

    onSubmit() {
        alert(JSON.stringify(this.data.name));
        this._freeApiService.insertFormadata().subscribe(
            data => {
                this.lstcomments = data;
            }
        );
    }

    constructor(private _freeApiService: freeApiService) {
    }

    lstcomments: Comments[];
    lstparacomments: Posts[];

    ngOnInit() {
        this._freeApiService.getcomments().subscribe(
            data => {
                this.lstcomments = data;
            }
        );
        this._freeApiService.getcommentsbyparameters().subscribe(
            data => {
                this.lstparacomments = data;
            }
        )
    }
}

Answer №1

Ensure your service method is set up as follows:

 formDataInsertion(name: string): Observable<any>{

Then, make the call:

this._apiService.formDataInsertion(this.details.name).subscribe(

For more information on functions and parameters, refer to this link

Answer №2

  1. Ensure that your service function is able to accept arguments.
insertFormData(data: any): Observable <any> {
  return this.httpclient.get("/api/api?type=savedata&fname=nilesh&tfvalue=js&mobile=6547896541&type_sec=1452&city=bhopal&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="37525a565e5b0a595c56455356435277505a565e5b1954585a">[email protected]</a>")
}
  1. Make sure that your app.component passes an argument to the method.
this._freeApiService.insertFormData(this.data).subscribe(data=>{this.lstcomments=data; });

Note: When saving data, it is recommended to use HTTP POST call.

You can achieve this in your freeapiservice by implementing something similar to the code snippet below:

insertFormData(data:any): Observable<any> {
  return this.httpclient.post("apiurl", data)
}

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

Angular2's docking layout control brings a sleek interface that rivals Telerik's RadDocking

I've been utilizing Telerik's RadDocking control within my Silverlight projects. Unfortunately, I haven't been able to find a similar docking layout control for Angular2. The closest alternative I found was angular2-grid. https://www.npmjs. ...

Using Optional Route Parameters in Angular with @ngrx

Just like the ngrx/example-app, I am in the process of developing a user interface that allows users to search for specific items by inputting a text string. I want to enhance the user experience by updating the URL with an optional parameter (query=searc ...

Value returned by Typescript

I have been attempting to retrieve a string from a typescript function - private _renderListAsync(): string { let _accHtml: string=''; // Local environment if (Environment.type === EnvironmentType.Local) { this._getMockLi ...

Encountering problem while executing ng build

Just completed my initial project in Angular 4, focusing solely on user login functionality. However, upon running ng build --prod, I encountered the following errors: Unable to determine versions of @angular/compiler-cli and typescript. The most common c ...

Guide: How to use multiple observables in resolver in Angular 4

I am looking for a way to retrieve multiple observables or results in my Angular application. Specifically, I want to first load a list of libraries and then load books based on the IDs of those libraries. I prefer not to call a service in the components, ...

We encountered a ReferenceError stating that 'dc' is not defined, despite having already imported d3, dc, and crossfilter in

In my current angular project, I have included the necessary imports in the component.ts file in the specific order of d3, crossfilter2, dc, and leaflet. Additionally, I have added the cdn for dc-leaflet.js in the index.html file. Despite these steps, wh ...

Utilizing NgRx 8 Actions in Conjunction with NgRx 7 Reducers: An Implementation

In the development of my new Angular 8 project, I have incorporated the NgRx library. It was mentioned to me that actions are created using createAction in NgRx 8, but reducers are built using NgRx 7. Initially, I implemented my reducer with NgRx 8, but no ...

Redirect to the identical component once the session has ended

I have a token-based API that expires after 10 minutes of user inactivity. When the token is changed due to idle time, an error response is received from the API and the user is redirected to the login page. Currently, when the user logs in again, they ar ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

Exploring React State Management: Leveraging the Context API as a centralized store for

Currently, I am developing a React web application using TypeScript. To enhance the State Management, I decided to implement React Hooks and Context API by following a concise tutorial that I came across here. Despite diligently following the tutorial, my ...

Utilizing the Controller with react-hook-form and material-ui to enhance the functionality of the FormControlLabel and

When using Material-ui with react-hook-form, it is recommended to use <Controller along with the render method instead of using "as = {xy-control}". Additionally, avoid mixing controller with inputRef = {register}. Using a single control is not an issue ...

Prevent using keys of nullable properties as method parameters in Typescript generics

What is the solution to disallow a method from accepting a parameter of type keyof this where the property is nullable? Consider the following example: abstract class MyAbstractClass { get<K extends keyof this>(key: K): this[K] { return this[k ...

Angular Module Federation -- The shared module is currently inaccessible for immediate use

Encountering a problem while attempting to execute tests on my Angular microfrontend for use within Module Federation. Using Angular 12 and Webpack 5. Uncaught Error: Shared module is not available for eager consumption: 5487 Any suggestions on how to co ...

Encountering an ENOENT error in the CodeSandbox CI environment, whereas this issue does not arise in GitHub

I am currently in the process of creating a GitHub pull request for the react-querybuilder library. However, I am encountering an issue with my CodeSandbox CI job, which is failing and displaying the following error message: { [Error: ENOENT: no such file ...

TypeScript does not verify keys within array objects

I am dealing with an issue where my TypeScript does not flag errors when I break an object in an array. The column object is being used for a Knex query. type Test = { id: string; startDate: string; percentDebitCard: number, } const column = { ...

Redefining the type of an existing function in Typescript: A step-by-step guide

If you're looking for a solution where you can declare an existing function without defining an expression, check out this article: . Rather than creating a new function, the goal is to declare the existing function in a similar manner without using t ...

Encountered an error - 'SyntaxError: unexpected token: ':'' while attempting to load a JSON file for ngx-translate using the Karma test runner

I am currently in the process of setting up system tests for my Angular application. The app utilizes the TranslateModule (ngx-translate) in this manner: TranslateModule.forRoot({ defaultLanguage: 'de', loader: { provide: Tra ...

How can I customize a Vue component slot in Storybook 8.0.6 using Vue 3.4 and Typescript to display various subcomponents within a story?

Incorporating a variety of sub-components into my Vue 3 component based on context is proving to be a challenge. Utilizing slots seems to be the solution in Vue 3, but I'm struggling to make it work within Storybook 8, which I'm using to showcase ...

The utilization of a JSON file string to define enum types results in an error stating that the type 'string' cannot be assigned to the type 'number' as mandated for calculated enum member values

In my code, I define an enum like this: export enum AccountSettings { accountManagement = "Account management", managementOfRelatives = 'Management of relatives', } Next, I have a file named en.json, which contains the correspondin ...

Display a collection of JSX elements within a React application

I've got a collection of JSX components named components: components = [ <span className="c1 c2" onClick={() => console.log("test")}>...</span>, <span className="c1 c2" onClick={() => console.log( ...