Ionic app getting data from url json - json

I don't know how to do this. I tried few examples from internet. What is the best solution?
import { Component } from '#angular/core';
#Component({
selector: 'page-hello-ionic',
templateUrl: 'hello-ionic.html'
})
export class HelloIonicPage {
constructor() {
}
}

to do this
Modify src/app/app.module.ts and import
import { HttpModule } from '#angular/http';
And Add to the Imports
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
After that you can use the HTTP Module from angular.
In your Page.ts
import the module and use it like this
import { Http } from '#angular/http';
constructor(public navCtrl: NavController, public http: Http) {
let url = "https://www.reddit.com/r/gifs/new/.json?limit=10";
this.http.get(url).map(res => res.json()).subscribe(data => {
console.log(data);
});
}
Additionally you can convert to returned JSON string to JSON Object
var jsonobject = JSON.parse(data)
And Alternatively you can use the IONIC NATIVE HTTP PLUGIN
Cheers :D

To do this just use the below code, no need to import any module
fetch('https://url.com').then(res => res.json())
.then(json => {
console.log(json)
});

Related

Module has no exported member 'http' [2305]

Hello I am trying to import http call from '#angular/common/http' and am getting error message that module has no exported member 'http'
Error:[ts] Module '"e:/car/node_modules/#angular/common/http"' has no exported member 'Http'. [2305]
import {
RouterModule
} from '#angular/router';
import {
BrowserModule
} from '#angular/platform-browser';
import {
NgModule
} from '#angular/core';
import {
AppRoutingModule
} from './app-routing.module';
import {
AppComponent
} from './app.component';
import {
HomeComponent
} from './home/home.component';
import {
HttpClientModule
} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
RouterModule.forRoot([{
path: '',
component: HomeComponent
}])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
import {
Http
} from '#angular/common/http';
import {
Component,
OnInit
} from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: Http) {}
products = [];
fetchData = function() {
this.http.get('http://localhost:5555/products').subscribe(
(res: Response) => {
this.products = res.json();
}
);
};
ngOnInit() {
this.fetchData();
}
}
the below code is used for inserting json file which includes the details
HttpClientModule will inject HttpClient service not the Http.
Please use HttpClient in constructor injection in the HomeComponent.
constructor(private http: HttpClient) {}
For Reference created sample stackblitz code.

Angular 6 component not showing up

I just started learning Angular yesterday so I apologize if I'm missing something obvious, but I am trying to display a component on the app.component.html, however, it is not showing up.
TS file for the component I am trying to display:
import { Component, OnInit } from '#angular/core';
import { ImageService } from '../shared/image.service';
#Component({
selector: 'image-list',
templateUrl: './image-list.component.html',
styleUrls: ['./image-list.component.css']
})
export class ImageListComponent implements OnInit {
images: any[];
constructor(private _imageService : ImageService ) { }
searchImages(query : string)
{
return this._imageService.getImage(query).subscribe
(
data => console.log(data),
error => console.log(error),
() => console.log("Request Completed!")
);
}
ngOnInit() {
}
}
image-list.component.html :
<button>Find Images</button>
app.component.html :
<image-list></image-list>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
image.service.ts
import { Injectable } from "#angular/core";
import { environment } from "../../environments/environment";
import { Http, Headers } from "#angular/http";
import { map, filter, scan } from 'rxjs/operators';
#Injectable()
export class ImageService
{
private query: string;
private API_KEY: string = environment.API_KEY;
private API_URL: string = environment.API_URL;
private URL: string = this.API_URL + this.API_KEY + '&q=';
constructor(private _http: Http) {
}
getImage(query)
{
return this._http.get(this.URL + this.query).pipe(
map((res) => res.json));
}
}
I had a similar problem trying to use a component outside its module.
In this case, you have to export a component from your .module.ts:
#NgModule({
// …
declarations: [ MyComponent ],
exports: [ MyComponent ],
// …
})
You need to import your Component and your Service into your app.module.ts and then to declarations and to providers property
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { ImageListComponent } from './image-list.component';
import { ImageService } from './image.service';
#NgModule({
declarations: [
AppComponent,
ImageListComponent
],
imports: [
BrowserModule
],
providers: [ ImageService ],
bootstrap: [AppComponent]
})
export class AppModule { }
Adjust ImageListComponent path into the import statement.
Teorically when you generate a component with Angular CLI with a command like this:
ng generate component image-list
it should update your app.module.ts file for you.
To generate a service use
ng generate service image
check this one
in src/app/app.module.ts
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, HttpClientModule],
bootstrap: [AppComponent],
})
export class AppModule {}
from this link: https://malcoded.com/posts/why-angular-not-works/
You may try the Angular tutorial from: https://angular.io/start . It shows how to render a custom Ansible component on the app.component.html page.
You just need to update the app.module.ts file. Assuming your component is named ImageListComponent:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router'; // add this line
import { AppComponent } from './app.component';
import { ImageListComponent } from './image-list/image-list.component'; // add this line
#NgModule({
declarations: [
AppComponent,
ImageListComponent // add this line
],
imports: [
BrowserModule,
// add the following 3 lines
RouterModule.forRoot([
{ path: '', component: ImageListComponent },
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
First try this, without adding any custom services.
It seems you have nothing that triggers the API call on your method searchImages in ImageComponent. Having a click eventListener on the <button>Find Images</button> tag should do the trick. Also register the ImageComponent and ImageService in your app.module.ts file.

get data from local Json file ionic 3 [duplicate]

This question already has answers here:
No provider for HttpClient
(25 answers)
Closed 5 years ago.
I start a dummy project in Ionic. I try to get data from a local Json file but I have this error :
I don't understand why there is no provider for HttpClient.
For further details, I actually tried to follow this tutorial : https://www.youtube.com/watch?v=vuc4dp0qHSc
How can I fix this error and get the data ?
Versions
Ionic 3.18.0
Angular 5.0.1
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { FirstPage } from '../pages/first/first';
import { CardsDataProvider } from '../providers/cards-data/cards-data';
#NgModule({
declarations: [
MyApp,
HomePage,
FirstPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
FirstPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
CardsDataProvider,
]
})
export class AppModule {}
cards-data.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
/*
Generated class for the CardsDataProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class CardsDataProvider {
constructor(public http: HttpClient) {
console.log('Hello CardsDataProvider Provider');
}
getLocalData() {
this.http.get('../assets/data/cards.json').map(res => res.json()).subscribe(data =>
{
console.log(data);
});
}
}
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FirstPage } from '../first/first';
import { CardsDataProvider } from '../../providers/cards-data/cards-data';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public CardsService: CardsDataProvider) {
}
openFirstPage() {
this.navCtrl.push(FirstPage);
}
ionViewDidLoad() {
this.CardsService.getLocalData();
}
}
Any help will be appreciated.
You are following an Ionic2 tutorial while using Ionic3 with Angular5.
For Http to work since Ionic 3.0, you need to include HttpClientModule in your imports in app.module.ts.
import {HttpClientModule} from '#angular/common/http';//import
#NgModule({
declarations: [
MyApp,
HomePage,
FirstPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpClientModule//include here
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
FirstPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
CardsDataProvider,
]
})
export class AppModule {}
Also, in your cards-data.ts,
import {Http} from '#angular/common/http';
#Injectable()
export class CardsDataProvider {
constructor(public http: HttpClient) { //change here
console.log('Hello CardsDataProvider Provider');
}
For further changes to go from Ionic 2 to 3 check here. For changes required to go to Angular 5 check here.
A simpler way is to find a more recent tutorial.

ng2-translate + Webpack for production

I'm trying to use the ng2-translate package with Webpack. In development mode it all works fine.
When i'm starting a build, it doesn't copy the language files to the "dist" directory.
Can anyone give me some advices how to change the output path, I tried to follow up https://github.com/ocombe/ng2-translate instructions but I doesnt provide any working example for webpack in production, and its not very clear how to use TranslateStaticLoader and change 18n/*.json.
If I add this I get an error with the libraries
#NgModule({
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
deps: [Http]
})
],
bootstrap: [AppComponent]
})
This is my app.module.ts
import {BrowserModule} from "#angular/platform-browser";
import { NgModule } from '#angular/core';
import {HttpModule} from '#angular/http';
import { AppComponent } from './app.component';
import {TranslateModule} from 'ng2-translate';
#NgModule({
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot()
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
My app.component.ts
import { Component } from '#angular/core';
import {TranslateService} from 'ng2-translate';
import '../../public/css/styles.css';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
param: string = "world";
constructor(translate: TranslateService) {
// this language will be used as a fallback when a translation isn't found in the current language
translate.setDefaultLang('en');
// the lang to use, if the lang isn't available, it will use the current loader to get them
translate.use('en');
}
}
My app.component.html
<div>{{ 'HELLO' | translate:{value: param} }}</div>
and my json
{
"HELLO": "hello {{value}}"
}
Thanks for your help.
What errors do you have ? I'm using it in development mode and it's working perfectly.

angular2-google-maps read apikey from web.config

We intergrated angular2-google-maps in our project. The project is built angularjs 2 release version and using webapi.
app.module.ts
import { LazyMapsAPILoaderConfig, AgmCoreModule } from 'angular2-google-maps/core';
import { appConfig,IAppConfig,GoogleMapApiKey } from "./app.config";
#NgModule({
imports: [
AgmCoreModule.forRoot({
apiKey: ""
})
],
declarations: [
AppComponent
],
providers: [
{ provide: LazyMapsAPILoaderConfig, useValue: GoogleMapApiKey }
],
bootstrap: [AppComponent]
})
export class AppModule {
}
app.config.ts
import { OpaqueToken } from "#angular/core";
export let appConfig = new OpaqueToken('app.config');
export interface IAppConfig {
apiKey: string
}
export const GoogleMapApiKey : IAppConfig = {
apiKey: "Key"
};
I hardcoded the google map api key in the typescript file. Is it possible to read it from .net web.config file.
Also is this correct way of displaying the map or can i make it part of component.
Any suggestions.