Parameter 'response' implicitly has an 'any' type in angular13 - angular13

I am new to angular ,I implementing a full stack project using angular
and springboot . I want to front fetch data from backend and show the
response.But when I try to show the response what comes from back end
but it throw an unwanted error .
Here is the error
Parameter 'response' implicitly has an 'any' type.ts(7006)
Here is the my code
userscomponent.ts
import { Component, OnInit } from '#angular/core';
import { User } from 'src/app/module/User';
import { HttpClientService } from 'src/app/service/http-client.service';
#Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
users : Array<User>|undefined;
constructor(private httpClientService : HttpClientService) { }
ngOnInit(){
this.httpClientService.getUsers().subscribe(
response => this.handleSuccessfulResponse(response),
);
}
handleSuccessfulResponse(response){
this.users = response;
}
}
I got exact error in my handlesuccessfulResponse function .response
parameter not support

Related

ionic 2 http post service is not working

hey i m new in ionic 2 http request, and facing problem in http post services, following is my code you please see and help me to finding problem.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Http, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
data:any;
name:any;
error:any;
constructor(public navCtrl: NavController, public http:Http) {
}
postit(){
var headers=new Headers();
headers.append('Content-Type', 'application/json');
var data = JSON.stringify({
username: "username",
password: "password"
});
this.http.post('url',JSON.stringify(data),{headers:headers})
.subscribe(res=>{
this.data=res.json();
this.name=this.data.userId;
console.log(res.json());
},
(err)=>{
this.error=err;
console.log("some error:",err);
});
}
}
url is of login page which need credentials. Is this code fine specially json data object.
please help me i have wasted my 4 days in this problem.
thank you.
You are calling JSON.stringify twice - once when you create the data and once when you send the POST. Remove the second one and leave only 'data'.

ionic calling a service

I defined a service in IONIC like this (file reddit.service.ts):
import {Injectable} from '#angular/core';
import {Http} from '#angular/http';
import 'rxjs/Rx';
#Injectable()
export class RedditService{
http:any;
baseUrl: String;
counstructor(http:Http){
this.http = http;
this.baseUrl = 'https://www.reddit.com/r';
}
getPosts(category, limit){
return this.http.get(this.baseUrl+'/'+category+'/top.json?limit='+limit).map(res => res.json());
}
}
I am calling this service like this (file reddits.ts):
getPosts(category, limit){
this.redditService.getPosts(category, limit).subscribe(response => {console.log(response);
});
The error Message I am getting is:
Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
at RedditService.getPosts (reddit.service.ts:16)
Why I am getting this error? What is wrong?
You have a typo:
counstructor(http:Http)
should be:
constructor(http:Http)
and usually we just inject providers into constructor like...
#Injectable()
export class RedditService{
baseUrl: String;
constructor(private http:Http){
this.baseUrl = 'https://www.reddit.com/r';
}
}
UPDATE:
As the HttpModule used to be included in the IonicModule before, it no longer is, and therefore the HttpModule needs to be imported in the NgModule and set in the imports array.
It seems like you have http service haven't injected properly inside Service constructor. Also make sure you have imported Http & Injectable injector correctly.
#Injectable()
export class RedditService {
//make sure you have below dependency inject with private access specifier.
//since we mentioned it private, http will be available in component context
constructor(private http: Http) { }
getPosts(category, limit){
return this.http.get(this.baseUrl+'/'+category+'/top.json?limit='+limit).map(res => res.json());
}
}
Additionally please add HttpModule in imports of your AppModule to make http API working.

how ionic framework get data from asp.net web api

I've created Asp.net Web API project .
When I browse http://localhost:55858/api/myData
it returns
<ArrayOfquoteMain>
<quoteMain>
<despt>Hello , data 1</despt>
<id>1</id>
<reference>Hello data 1</reference>
</quoteMain>
<quoteMain>
<despt>Hello , data 2</despt>
<id>2</id>
<reference>Hello data 2</reference>
</quoteMain>
<quoteMain>
<despt>Hello , data 3</despt>
<id>3</id>
<reference>Hello data 3</reference>
</quoteMain>
</ArrayOfquoteMain>
I just want to show this data as a list in my ionic app .
I've created Ionic app using ionic start ionic2-http blank --v2.
But I don't know how to use with my asp.net web API.
You will need to create apiService from your ionic project.
for example:
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams} from '#angular/common/http';
#Injectable()
export class apiService{
constructor(private http: HttpClient) { }
serviceBaseUrl:string = http://localhost:55858/';
getData(){
let apiUrl = `${this.serviceBaseUrl}api/myData`;  
return this.http.get<any>(apiUrl);
}
}
Which you will then call it from any component using below code:
getData() {
this.apiService.getData().subscribe(
data => {
var myData = data;
console.log(myData);
},
error => console.error(error),
() => {
})
}
Is the error you are getting No 'Access-Control-Allow-Origin'...? If so you need to handle CORS in your ionic project.
CORS is only an issue when we are running or testing our app when running ionic serve.
To enable this in your ionic project, modify the ionic.config.json to include the proxies tag:
{
"name": "myionicproj",
"app_id": "",
"v2": true,
"typescript": true,
"proxies": [
{
"path": "/api",
"proxyUrl": "http://localhost:55858/api"
}
]
}
The proxy URL is the url of your .NET web api running locally. You can replace it with your environment url.
To view the results in console.log in your typescript class:
import { Component } from '#angular/core';
import {Http} from "#angular/http";
import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public http: Http) {
this.http.get('http://localhost:8100/api/myData').map(res => res.json()).subscribe(data => {
console.log(data);
});
}
}
http://localhost:8100 is your ionic localhost. It proxy the .net web api http://localhost:55858/api end point via your local ionic server http://localhost:8100/api

How to process http-Calls in Angular2/Ionic2

I'm currently trying to set up the Rest-API for my Ionic2 Application. As backend I'm using Crud-API which is working fine already. But I'm running into problems when calling the API from the APP.
I'm using the following class as a service to make the http call:
import {Http, Response} from '#angular/http';
import 'rxjs/add/operator/map';
export class NoteService {
static get parameters() {
return [[Http]];
}
constructor(private http:Http) {
}
searchNotes() {
var url = 'http://localhost/plotnote/api_crud.php/note/1';
var response = this.http.get(url).map(res => res.json());
return response;
}
}
Then I use the searchNotes-Method of this service to get the results and write them in the array notes:
import {Component} from '#angular/core';
import {NavController} from 'ionic-angular';
import {NoteService} from '../services/NoteService';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [NoteService]
})
export class HomePage {
notes: Array<any>;
constructor(private navController: NavController, private noteService: NoteService) {
this.listNotes();
console.log("notes: " + this.notes);
}
listNotes() {
this.noteService.searchNotes().subscribe(
data => {
this.notes = data.results;
console.log('Data: ');
console.log(data);
},
err => {
console.log(err);
},
() => console.log('Note Search Complete')
);
}
}
Finally to display the notes I do the following:
<ion-content class="home" padding>
<ion-list>
<ion-card *ngFor="let note of notes">
<ion-card-content>
{{note.text}}
</ion-card-content>
</ion-card>
</ion-list>
</ion-content>
Sadly this doesn't work at all :(.
I tried to find the problem through the js-console and it looks like I'm getting the right data from the api, but there seems to be a problem with putting the data into the notes-Array.
Here is a screenshot of the console-output:
js-console output
I hope you guys can help me to find the problem and get this thing working :)

Injected service is undefined right in the constructor

For the note, I'm quite uninitiated to Angular (1 or 2 for that matter).
I'm trying to write a "super" layer of Http to avoid having to put the same headers everywhere.
import {Http, ConnectionBackend, RequestOptions, Response, Headers} from '#angular/http';
import {Observable} from 'rxjs';
import {LoadingService} from "../../services/loading.service";
export class HttpLoading extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions,
private _ls: LoadingService )
{
super(backend, defaultOptions);
}
getPostPutHeader() {
var authHeader = new Headers();
authHeader.append("Authorization", "Bearer "+ localStorage.getItem('token') );
authHeader.append('Content-Type', 'application/json');
return authHeader;
}
post(url: string, data:any):Observable<Response> {
this._ls.isLoading = true; // Exception here: this._ls is undefined
return super.post(url, data, { headers: this.getPostPutHeader() })
.map(res => {
this._ls.isLoading = false;
return res;
});
}
}
And a service to tell when a request is executing; it's injected in the above class HttpLoading.
import {Injectable} from '#angular/core';
#Injectable()
export class LoadingService {
isLoading: boolean = false;
}
I have a bunch of stuff in my bootstrap, including HttpLoading, LoadingService and ConnectionBackend (for this last one, I get an exception if it's not here).
bootstrap(AppComponent, [
ConnectionBackend,
HttpLoading,
APP_ROUTER_PROVIDERS,
HTTP_PROVIDERS,
LoadingService,
disableDeprecatedForms(),
provideForms()
])
The problem is that the first time I call HttpLoading's post method (in yet another service), I get an exception at this._ls.isLoading, because this._ls is undefined, and I can't figure why.
Please tell me if you need more information.
Edit
LoadingService is correctly injected in my AppComponent (main component).
//imports
//#Component
export class AppComponent {
requesting:boolean = false;
constructor(public authService: AuthService, private router: Router, private _ls: LoadingService) {
}
navigate(route:string) {
this._ls.isLoading = true;
this.router.navigate([route])
.then(() => this._ls.isLoading = false);
}
}
Potential solution
It seems that your public/private parameters must be placed first in the list. I'll let someone more skilled than me explain why, though...
export class HttpLoading extends Http {
constructor(private _ls: LoadingService, backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
I would configure your HttpLoading class this way in the providers when bootstrapping your application:
bootstrap(AppComponent, [
(...)
HTTP_PROVIDERS,
{
provide:Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, loadingService: LoadingService) => {
return new HttpLoading(backend, defaultOptions, loadingService);
},
deps: [XHRBackend, RequestOptions, LoadingService]
}
]);
The reason for this is that you want to use your own class for the Http provider. You need to change the class behind the Http provider by your HttpLoading class. Be careful to define it after HTTP_PROVIDERS.
To be able to inject the instance of XHRBackend to your class, you need to use useFactory...
Ok , I know that may seem trivial, but try to create a variable and initialize it in the constructor
To extend #Thierry Templier's answer. I am using Angular v4, and my experience is that you need to provide ALL the dependencies that your extending constructor needs, AND in the right order - I guess it's a legacy way of doing it, from angular 1.x.
My example:
// This is my extended class (relevant part only)
#Injectable()
export class HttpService extends Http {
constructor(
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private router: Router,
private loaderService: LoaderService,
private modalService: ModalService,
private localStorageService: LocalStorageService
)
{
super(backend, defaultOptions)
}
// This is the provider factory defined in app.module.ts:
export function httpClientFactory(
backend: XHRBackend,
defaultOptions: RequestOptions,
router: Router,
loaderService: LoaderService,
modalService: ModalService,
localStorageService: LocalStorageService
) : Http
{
return new HttpService(
backend,
defaultOptions,
router,
loaderService,
modalService,
localStorageService
);
}
This is the configuration (just left the relevant part) in app.module.ts:
providers: [
ModalService
LocalStorageService,
LoaderService,
{
provide: HttpService,
useFactory: httpClientFactory,
deps: [XHRBackend, RequestOptions, Router, LoaderService, ModalService, LocalStorageService]
}
Note: notice the order of declaring the deps in the config compared to the factory constructor .. it is the same

Resources