Migrating from Ionic 3 to Ionic 5 - Json functions on user-data - json

Hello i am trying to migrate from Ionic Cordova 3 to 5.
I want to put a call a php function to get results. PHP works fine.
this is what i did to call the results.
home.ts
allMediaSet(){
console.log('dddd1');
this.offset = 0;
this.userData.allMedias(this.offset)
.map(res => res.json())
.subscribe(data => {
if (data.success) {
this.allMedia = data.mediaFeed;
}
});
}
user-data.ts function
allMedias(offset: number) {
console.log('ddd');
let url = this.appData.getApiUrl() + 'allMedia';
let data = this.jsonToURLEncoded({
api_signature: this.api_signature,
offset: offset
});
return this.http.post(url, data, this.options);
}
this is the error i am getting
core.js:6014 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[Platform]:
StaticInjectorError(Platform: core)[Platform]:
NullInjectorError: No provider for Platform!
NullInjectorError: StaticInjectorError(AppModule)[Platform]:
StaticInjectorError(Platform: core)[Platform]:
NullInjectorError: No provider for Platform!
app.module.ts
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { InAppBrowser } from '#ionic-native/in-app-browser/ngx';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { IonicModule } from '#ionic/angular';
import { IonicStorageModule } from '#ionic/storage';
import { Platform} from 'ionic-angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ServiceWorkerModule } from '#angular/service-worker';
import { environment } from '../environments/environment';
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
BrowserModule,
AppRoutingModule,
Platform,
HttpClientModule,
FormsModule,
IonicModule.forRoot(),
IonicStorageModule.forRoot(),
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: environment.production
})
],
declarations: [AppComponent],
providers: [InAppBrowser, SplashScreen, StatusBar],
bootstrap: [AppComponent]
})
export class AppModule {}
login.ts (has the results i want to return)
import { Component } from '#angular/core';
import { NgForm } from '#angular/forms';
import { Router } from '#angular/router';
import { UserData } from '../../providers/user-data/user-data';
import { UserOptions } from '../../interfaces/user-options';
#Component({
selector: 'page-login',
templateUrl: 'login.html',
styleUrls: ['./login.scss'],
})
export class LoginPage {
resposeData: any;
loginData: any = {};
allMedia:any =[];
mediaType:string = '';
offset: number = 0;
login: UserOptions = { username: '', password: '' };
submitted = false;
constructor(
public userData: UserData,
public router: Router,
)
{
this.allMediaSet();
}
allMediaSet(){
console.log('dddd1');
this.offset = 0;
this.userData.allMedias(this.offset)
.subscribe(data => {
console.log(data);
});
}
onLogin(form: NgForm) {
this.submitted = true;
if (form.valid) {
this.userData.login(this.login.username);
this.router.navigateByUrl('/app/tabs/schedule');
}
}
}
any help?

Your question seems like not Ionic specific but it is about Angular. Since good old Ionic 3 / Angular 4 days, Angular moved on from Http to HttpClient.
Please see here: https://angular.io/guide/http#setup
You need to ensure you migrate your Angular code to use the latest HttpClientModule:
https://devops.datenkollektiv.de/migrating-from-angular-httpmodule-to-new-angular-43-httpclientmodule.html
In short:
replace 'Http' with 'HttpClient':
import {Http} from '#angular/http';
becomes
import { HttpClient } from '#angular/common/http';
Remove manual extraction of JSON via map operator:
this.userData.allMedias(this.offset).map(res => res.json())
becomes
this.userData.allMedias(this.offset)

Related

ERROR TypeError: Cannot read properties of undefined (reading 'getProfile')

I am trying to display data from a local json file to a table with angular 12, but first step I just want to console data from that file. But I found the error like I wrote in the title.
Here is my code:
app.module.ts:
import {NgModule} from '#angular/core';
import {BrowserModule} from '#angular/platform-browser';
import {BrowserAnimationsModule} from '#angular/platform-browser/animations';
import {MaterialExampleModule} from '../material.module';
import {TablePaginationExample} from './table-pagination-example';
import {FormsModule, ReactiveFormsModule} from '#angular/forms';
import {MatNativeDateModule} from '#angular/material/core';
import {HttpClientModule} from '#angular/common/http';
#NgModule({
declarations: [TablePaginationExample],
imports: [
BrowserAnimationsModule,
BrowserModule,
FormsModule,
HttpClientModule,
MatNativeDateModule,
MaterialExampleModule,
ReactiveFormsModule,
],
providers: [],
bootstrap: [TablePaginationExample],
})
export class AppModule {}
table-pagination-example.ts:
import {AfterViewInit, Component, OnInit, ViewChild} from '#angular/core';
import {MatPaginator} from '#angular/material/paginator';
import {MatTableDataSource} from '#angular/material/table';
import { ServerHttpService } from './Services/server-http.service';
/**
* #title Table with pagination
*/
#Component({
selector: 'table-pagination-example',
styleUrls: ['table-pagination-example.css'],
templateUrl: 'table-pagination-example.html',
})
export class TablePaginationExample implements OnInit {
private serverHttp: ServerHttpService;
displayedColumns: string[] = ['secCd', 'secType', 'secSName', 'secName', 'capitalValue', 'listedQty', 'foreignMaxQty', 'stockDividendRate', 'cashDividendRate', 'marketCd', 'tradingLot', 'parValue', 'maxRoom', 'status', 'remarks'];
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
#ViewChild(MatPaginator) paginator: MatPaginator;
ngOnInit(): void {
this.dataSource.paginator = this.paginator;
this.serverHttp.getProfile().subscribe((data) => {
console.log(data);
})
}
}
export interface PeriodicElement {
// action: string,
// secCd: string,
// secType: string,
// secSName: string,
// secName: string,
// capitalValue: number,
// listedQty: number,
}
const ELEMENT_DATA: PeriodicElement[] = []
server-http.service.ts:
import { HttpClient, HttpErrorResponse, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { catchError, Observable } from 'rxjs';
import { throwError } from 'rxjs/internal/observable/throwError';
#Injectable({
providedIn: 'root'
})
export class ServerHttpService {
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
}
private REST_API_SERVER = 'http://localhost:3000'
constructor(private httpClient: HttpClient) { }
public getProfile(): Observable<any> {
const url = `${this.REST_API_SERVER}/profile`;
return this.httpClient
.get<any>(url, this.httpOptions)
.pipe(catchError(this.handleError));
}
private handleError(error: HttpErrorResponse) {
if (error.status === 0) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong.
console.error(
`Backend returned code ${error.status}, body was: `, error.error);
}
// Return an observable with a user-facing error message.
return throwError(() => new Error('Something bad happened; please try again later.'));
}
}
Here is the picture of console screen:
image
Thank u for your attention and if there are any problem with my question or my English, please let me know. This is the first time I post a question to Stackoverflow.
You have to remove private serverHttp: ServerHttpService; and add the following code instead.
constructor(private serverHttp: ServerHttpService) {}
You can read about the dependency injection of Angular services in detail here.

Logout From website if user does not do any activity in our web from Last 15 minutes

how to Logout From website if user does not do any move in our web from 15 minutes?
In Your angular app
npm install --save #ng-idle/core #ng-idle/keepalive angular2-moment
Set up your application module
Open src/app/app.module.ts and import the Ng2IdleModule using
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { NgIdleKeepaliveModule } from '#ng-idle/keepalive'; // this includes the core NgIdleModule but includes keepalive providers for easy wireup
import { MomentModule } from 'angular2-moment'; // optional, provides moment-style pipes for date formatting
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MomentModule,
NgIdleKeepaliveModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Extend your Main component
import { Component, OnInit } from '#angular/core';
import { Router, NavigationStart } from '#angular/router';
import { Idle, DEFAULT_INTERRUPTSOURCES } from '#ng-idle/core';
import { Keepalive } from '#ng-idle/keepalive';
#Component({
selector: 'app-theme',
templateUrl: './theme.component.html',
styleUrls: ['./theme.component.css']
})
export class AppComponent implements OnInit {
lastPing?: Date = null;
constructor(private route: Router, private idle: Idle, private keepalive: Keepalive) {
idle.setIdle(5);
idle.setTimeout(900);
idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);
idle.onIdleEnd.subscribe(() => { });
idle.onTimeout.subscribe(() => {
this.logout();
});
idle.onIdleStart.subscribe(() => {
});
idle.onTimeoutWarning.subscribe((countdown) => {
});
keepalive.interval(5);
keepalive.onPing.subscribe(() => this.lastPing = new Date());
this.reset();
}
ngOnInit() {
}
reset() {
this.idle.watch();
}
logout() {
//--
// LogoutCode
//---
}
}

Angular 8: not able to get message from Rest Api

I used following links https://grokonez.com/python/django-angular-6-example-django-rest-framework-mysql-crud-example-part-2-django-server and https://grokonez.com/frontend/django-angular-6-example-django-rest-framework-angular-crud-mysql-example-part-3-angular-client to create a django rest API and angular app that calls this rest.
Considering that I'm new in such kind of development so I created as a first step an App that just displays customers list.
Django rest API is fine working. I tested it with the browser:
But my problem is with the angular app, seems that it's not able to get message with the same URL: http://localhost:8000/customers
Below is my angular code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomersListComponent } from './customers-list/customers-list.component';
#NgModule({
declarations: [
AppComponent,
routingComponents,
CustomersListComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { CustomersListComponent } from './customers-list/customers-list.component';
const routes: Routes = [
{ path: 'customers', component: CustomersListComponent },
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
customer.ts
export class Customer {
id: number;
name: string;
age: number;
active: boolean;
}
customer.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class CustomerService {
private baseUrl = 'http://localhost:8000/customers';
constructor(private http: HttpClient) { }
getCustomersList(): Observable<any> {
return this.http.get(`${this.baseUrl}/`);
}
}
customers-list.component.ts
import { Component, OnInit, Input } from '#angular/core';
import { Observable } from 'rxjs';
import { CustomerService } from '../customer.service';
import { Customer } from '../customer';
#Component({
selector: 'app-customers-list',
templateUrl: './customers-list.component.html',
styleUrls: ['./customers-list.component.css']
})
export class CustomersListComponent implements OnInit {
customers: Observable<Customer[]>;
constructor(private customerService: CustomerService) { }
ngOnInit() {
console.log("Hellllllllo from customers-list.component.ts ngOnInit");
this.reloadData();
}
reloadData() {
this.customers= this.customerService.getCustomersList();
}
}
customers-list.component.html
<h1>Customers {{JSON.stringify(this.customers)}}</h1>
<div *ngFor="let customer of customers" style="width: 300px;">
<h2>Hello iii</h2>
<div>
<label>Name: </label> {{customer.name}}
</div>
<div>
<label>Age: </label> {{customer.age}}
</div>
<div>
<label>Active: </label> {{customer.active}}
</div>
</div>
The result that got when calling /customers from the browser is the following:
"Routing and Navigation" message is coming from app.component.html
As you can see message Customers is displayed but everything that corresponds to the variable customers (which is the list of customers) is not displayed.
Has someone an idea what's the main cause of this issue? and how I can fix it?
Thank you in advance
You should subscribe to get the response from the API because http.get returns an observable, observable invokes only when you subscribe to it. try the following method
reloadData() {
this.customerService.getCustomersList().subscribe((res: any) => {
this.customers = res;
});
}
In your service
getCustomersList(): Observable<any> {
return this.http.get(`${this.baseUrl}/`);
}
This function returns an observable
So you should subscribe to it like this to make the request
this.customerService.getCustomersList().subscribe((res: any) => {
this.customers = res;
});
Or in your html file you can add async pipe like this
*ngFor="let customer of customers | async

How to get data from a rest api into my view - Angular 6

I have a Angular 6 application, I would like to connect some rest api data into my application. I have written a service for this. The rest api is: https://demo1049220.mockable.io/api/incident. Which takes in data from a results object. So far I have the following code but it does not work as the data is not showing in the table:
Also error in console is: Uncaught TypeError: Cannot read property 'ngOriginalError' of undefined
Service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse, HttpErrorResponse } from '#angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class nowService {
serviceApiUrl: string = 'https://demo1049220.mockable.io/api/incident';
constructor(
private http: HttpClient,
) { }
getAll(): Observable<any> {
return this.http.get<any>(this.serviceApiUrl)
.pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log(error.error.message)
} else {
console.log(error.status)
}
return throwError(
console.log('Something has happened; Api is not working!!'));
};
}
Component.ts
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '#angular/common/http';
// Services
import { nowService } from '../../services/servicenow.service';
#Component({
selector: 'app-service-incident',
templateUrl: './service-incident.component.html',
styleUrls: ['./service-incident.component.scss']
})
export class ServiceIncidentComponent implements OnInit {
public incidents: any;
public loading = true;
public errorApi = false;
constructor(private service: nowService) {
}
ngOnInit() {
this.service.getAll().subscribe((data) => {
this.loading = true;
this.incidents = data;
this.loading = false;
console.log('Result - ', data);
console.log('data is received');
})
}
}
Table in html to list the data
<tbody>
<tr class="" *ngFor="let incident of incidents">
<td><input type="radio" name="gender">
<i class="form-icon mr-5"></i>{{incident.u_serial_number}}</td>
<td>{{incident.u_product_name}}</td>
<td>{{incident.u_address_floor}}</td>
<td>{{incident.u_address_line_1}}</td>
<td>{{incident.u_address_post_code}}</td>
</tr>
</tbody>
You have to import your HttpClientModule in your app module, code:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpClient, HttpClientModule } from '#angular/common/http';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
#NgModule({
imports: [ BrowserModule, FormsModule, HttpClientModule ],
providers: [HttpClient, ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
and use data.result in your ngFor loop, check this:
ngOnInit() {
this.service.getAll().subscribe((data) => {
this.loading = true;
this.incidents = data.result;
this.loading = false;
console.log('Result - ', data.result);
console.log('data is recieved');
})
}
Can you check if the console is displaying some error ? (Ctrl+Shift+I on Google Chrome, then click on Console)

get JSON data at click a button using promises

I'm receiving JSON data using promises and it works. But now I want to implement a button who call again API (any time that you call API you get different values) how can I do it?
quotes-provider.ts
import { Injectable } from "#angular/core";
import { Http } from '#angular/http';
import { Quote } from './quote.model';
import 'rxjs/add/operator/map';
import { resolve } from "path";
import { reject } from "q";
#Injectable()
export class QuotesProvider {
private quote: Quote;
constructor(private http: Http) {
}
public getQuote(): Quote {
return this.quote;
}
load() {
console.log("loading data...");
return new Promise((resolve, reject) => {
this.http
.get('http://quotes.stormconsultancy.co.uk/random.json')
.map(res => res.json())
.subscribe(response => {
this.quote = response;
console.log("loading complete");
resolve(true);
})
})
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '#angular/core';
import { AppComponent } from './app.component';
import { QuoteBoxComponent } from './quote-box/quote-box.component';
import { QuotesProvider } from './quote-box/quotes-provider';
import { HttpModule } from '#angular/http';
export function quotesProviderFactory(provider: QuotesProvider) {
return () => provider.load();
}
#NgModule({
declarations: [
AppComponent,
QuoteBoxComponent
],
imports: [
BrowserModule,
HttpModule
],
providers: [
QuotesProvider,
{ provide: APP_INITIALIZER, useFactory: quotesProviderFactory, deps: [QuotesProvider], multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
quote-box.component.ts
#Component({
selector: 'app-quote-box',
templateUrl: './quote-box.component.html',
styleUrls: ['./quote-box.component.css']
})
export class QuoteBoxComponent implements OnInit {
// #HostBinding('class.quote-box') quoteBox = true;
// http://quotes.stormconsultancy.co.uk/random.json
quote: Quote;
constructor(public quotesProvider: QuotesProvider) {
this.quote = quotesProvider.getQuote();
}
ngOnInit() {
console.log(this.quote.author);
}
// here I want to call API again
newQuote() {
}
}
I'm following this tutorial to do this https://devblog.dymel.pl/2017/10/17/angular-preload/
I dont know what exactly you want to do but if i understeand it right I dont know why are u doing this in that way. I would just create service and then inject to your components and use it on button click. Maybe tutorial is a little bit outdated.
quotes.service.ts
import { Injectable } from '#angular/core';
import { HttpHeaders, HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable()
export class QuotesService {
constructor(private http: HttpClient) { }
getQuotes() {
return this.http.get('http://quotes.stormconsultancy.co.uk/random.json',
httpOptions);
}
}
Then in your component in method called on button click
Constructor
constructor(private quotesService : QuotesService) { }
In method called on button click
this.quotesService.getQuotes().subscribe(quotes => {
// do what you want with your qoutes
});