Call 2 objects from API on button click ionic2 - angularjs

I got an API link where i want to get 2 objects from but it's my first time in Ionic2 so I don't know how I can create the function to call them.
I have my homepage with my button
<ion-content >
<button ion-button (click)="getObjects()"><ion-icon name="get"></ion-icon>Get</button>
</ion-content>
And in my home.ts file I've tried something like this:
import { Component } from '#angular/core';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
import { NavController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
static get parameters() {
return [[Http]];
}
constructor(public http:Http) {
}
getObjects(objectNames)
var url = 'MYurl';
var response = this.http.get(url).map(res => res.json());
return response;
}
The objects I want to call are like this:
{"lat","long","deviceID","value","id"}
Someone who can help to create the right function?

What you are getting in response variable is an Observable. You will only get the response if you subscribe to it
getObjects(objectNames) {
var url = 'MYurl';
this.http.get(url).map(res => res.json()).subscribe((response) => {
console.log(response);
}
}
You can read this if you want more details :
https://scotch.io/tutorials/angular-2-http-requests-with-observables

Related

Angular 6 - Display data from database with *ngFor

I'm trying to display datas from a database. I've found examples on the internet but it's not working at all
Error from Eclipse:
java.lang.IllegalArgumentException: id to load is required for loading
My html file:
<ul>
<li *ngFor="let questionnaire of questionnaires | async">{{questionnaire.name}}</li>
</ul>
My typeScript file:
import { Injectable } from '#angular/core';
import { Component, OnInit, Input } from '#angular/core';
import {QuestionnaireService} from '../services/questionnaire.service';
#Injectable()
#Component({
selector: 'app-qcm',
templateUrl: './qcm.component.html',
styleUrls: ['./qcm.component.sass']
})
export class QcmComponent implements OnInit {
#Input()
questionnaires :any = [];
constructor(private questionnaireService: QuestionnaireService) { }
ngOnInit() {
this.questionnaires = this.questionnaireService.getQuestionnaire(1);
}
}
My service:
import {environment} from '../../environments/environment';
import {Injectable} from '#angular/core';
import {HttpClient} from '#angular/common/http';
#Injectable({providedIn: 'root'})
export class QuestionnaireService {
user: any;
constructor(private http: HttpClient) {}
getQuestionnaire(id: number) {
return this.http.get<any>(`${environment.apiUrl}getQuestionnaire`);
}
}
Here is my webservice methode (spring hibernate)
#GET
#Path("/getQuestionnaire")
public Questionnaire getQuestionnaire(#QueryParam("id") Long id) throws Exception {
return FacadeBackOffice.getInstance().getQuestionnaireService().getQuestionnaire(id);
}
TODO list:
Check if the api call goes to the right URL.
Howto: Check the request and response on network tab.
questionnaires in your component is an Observable and not an array.
Why: HttpClient get returns an Observable, so you have two choices:
use the async pipe (you are doing it the right way)
subscribe to the observable to send the request and in the anonymous function passed to the subscribe assign questionnaires class variable with the response (or subset).
Improvement:
Makes no sense to populate questionnaires class variable two ways (Input of the component and result of a http get request). Leave only one option here.
you might be facing asynch data call issue.
Please try subscribing to your service and then storing the data to your array. e.g.
ngOnInit() {
this.questionnaireService.getQuestionnaire()
.subscribe(
(data) => {
this.questionnaires= data;
});
}
Try taking the async out of the html, and then putting a .subscribe() on the the service instead. Also, remove the #Input(), it looks like it is unneeded since your component's ngOnInit will be populating the array.
I added a console.log() so you know what is in your service call in case you might need something like this.questionarries = response.body.
html
<ul>
<li *ngFor="let questionnaire of questionnaires">{{questionnaire.name}}</li>
</ul>
component
import { Injectable } from '#angular/core';
import { Component, OnInit, Input } from '#angular/core';
import {QuestionnaireService} from '../services/questionnaire.service';
#Injectable()
#Component({
selector: 'app-qcm',
templateUrl: './qcm.component.html',
styleUrls: ['./qcm.component.sass']
})
export class QcmComponent implements OnInit {
questionnaires :any = [];
constructor(private questionnaireService: QuestionnaireService) { }
ngOnInit() {
this.questionnaireService.getQuestionnaire().subscribe(
response => {
this.questionnaires = response;
console.log(this.questionnaries);
}
);
}
}

Angular2 Typescript View not updating data after save changes and update the array (model)

I have parent component which call a REST api to get profile (JSON) data. the parent component pass this data to child component using input (array) to create dynamic form (input fields). All fields have been created successfully. the form is saving the data to DB using API post.
Problem: If the user navigate to home page and come back to profile dynamic form the data value is showing with the data version before save (old version of the data). If I refresh the screen, then I can get the correct data. the view has not been updated when load the form again. I checked the log and the JSON data being returned updated, but the form is getting the previous version of the values.
Parent Html
<df-profile [profileData]="profileData"></df-profile>
Parent Component
import { Component, ChangeDetectorRef, Input, OnInit} from '#angular/core';
import { Http } from '#angular/http';
import { Router } from '#angular/router';
import { AuthenticationService, UserService } from '../services/index';
import { ProfileModel } from '../models/index';
#Component({
moduleId: module.id,
selector: 'user-profile',
templateUrl: 'user.profile.component.html'
})
export class UserProfileComponent implements OnInit {
profileData: ProfileModel[] = [];
public isDataAvailable: boolean = false;
constructor(
public router: Router,
private userService: UserService,
private authenticationService: AuthenticationService,
) {}
ngOnInit() {
console.info("Starting GameDay Component ngOnInit ... ...");
console.info(this.authenticationService.isLoggedIn());
if (this.authenticationService.isLoggedIn()) {
this.getData().then(() => this.isDataAvailable = true);
} else {
this.authenticationService.logout();
}
}
getData(): Promise<ProfileModel<any>[]> {
return this.userService.get.profile().then(data => {
this.profileData = data[0]['profileList'];
});
}
}
Child Dynamic Form Html
<form (ngSubmit)="form.valid && onSubmit()" [formGroup]="form">
<div class="kode-team-match" *ngFor="let item of profileData">
<ul>
<li class="home-kode-field"><df-field [field]="item.field" [form]="form"></df-field></li>
</ul>
<div class="clearfix"></div>
</div>
<div class="form-group">
<div class="col-md-12" style="text-align:center;">
<button type="submit" [disabled]="loading" class="kode-modren-btn thbg-colortwo"> Salvar</button>
</div>
</div>
</form>
<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
Child Dynamic Form Component
import { Component, Input, ChangeDetectorRef, OnInit } from '#angular/core';
import { FormControl, FormGroup } from '#angular/forms';
import { AuthenticationService, UserService } from '../services/index';
#Component({
moduleId: module.id,
selector: 'df-profile ',
templateUrl: 'profile.form.component.html',
providers: [ProfileControlService]
})
export class ProfileFormComponent implements OnInit {
#Input() profileData: ProfileModel[];
form: FormGroup;
payLoad = '';
constructor(
private pcs: ProfileControlService,
) {
this.profileData = [];
}
ngOnInit() {
//console.log('Starting form component ... ...');
this.form = this.pcs.toFormGroup(this.profileData);
}
onSubmit() {
this.userService.saveUserProfile(array)
.subscribe(result => {
this.isFailed = result;
if (result === true) {
this.service.success(this.translate.instant('register login'), this.translate.instant('register success'));
} else {
this.error = this.userService.errorMessage;
}
this.loading = false;
});
}
}
I'm struggling to see what I'm doing wrong here. Can anyone help?
I don't know if I need to invoke change detection and where.

Undefined Data When Calling From JSON in Ionic 2

I have a firebase URL to get some test data from as I'm still learning Ionic 2. Originally I had the error 'No HTTP Provider', but I fixed that by adding HttpModule to the app.module.ts file, but since that my data is always coming back as undefined.
The service is in it's own file (ww-api.service.ts):
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
#Injectable()
export class WildWalkApi {
private baseUrl = 'https://i2test-ea07c.firebaseio.com/';
constructor(private http: Http) {}
getLoginTest(){
return new Promise(resolve => {
this.http.get(this.baseUrl + 'login.json')
.subscribe(res => resolve(res.json()));
});
}
}
Then this is exported using a shared file (shared.ts):
export * from './ww-api.service';
This then goes into app.componant.ts:
import { WildWalkApi } from './shared/shared';
#Component({
templateUrl: 'app.html',
providers: [
WildWalkApi,
HttpModule
]
})
And finally I try and use the data in my view:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { WildWalkApi } from "../../app/shared/shared";
#IonicPage()
#Component({
selector: 'page-home-logged-in',
templateUrl: 'home-logged-in.html',
})
export class HomeLoggedIn {
private login;
constructor(public navCtrl: NavController, public navParams: NavParams, private wwapi: WildWalkApi) {
}
ionViewDidLoad() {
this.wwapi.getLoginTest().then(data => this.login = data);
console.log('ionViewDidLoad HomeLoggedIn ' + this.login);
}
}
However this.login is always coming back as undefined.
In your code You're trying to print the value right after sending the request but data is not available at that time .
You can use Event for it . Refer http://ionicframework.com/docs/api/util/Events/
sample is here
In that file from where you want to use that event is
this.events.publish('user:loggedIn', data);
and that file where you want to show that data is
this.events.subscribe('user:loggedIn', (data) => {
console.log("page 1 data "+data);
this.page1Message=data;
});
This may work for you .

get json data from service to page in ionic 3

I'm trying to load a JSON from remote server which I already obtained in a service using http.get(), but I can't get the data from my service into my page. I can see the json data is loaded in the service in console.log but can't find a way to get it into my page so I can use those data in my UI. Does anybody see what i'm doing wrong here?
here is the code of my service
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
#Injectable()
export class MyService {
returnedData;
constructor(public http: Http) {
console.log('Hello MyService Provider');
}
getRemoteData(){
console.log('Hello inside getRemoteData');
this.http.get('https://randomuser.me/api/?inc=gender,name,email,phone,picture,location').map(res => res.json()).subscribe(data => {
console.log(data);
this.returnedData=data;
});
return returnedData;
}
}
here is my page
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { MyService } from '../../providers/my-service';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
myJson;
constructor(public navCtrl: NavController, public serviceOne: MyService) {
}
ionViewDidload(){
console.log('Hello MyService called');
this.myJson=this.serviceOne.getRemoteData;
console.log('myJson');
}
getRandomSpan(){
return Math.floor((Math.random()*10)+1);
};
}
I want to get the value of the json I received from server into myJson variable.
so I can use those data into UI.

Trying to execute component function after auth.login() with Facebook Auth0 Angular 2

I'm trying to execute a component function after Auth0 logs someone in via Facebook authentication. I'm trying to have that component function send a POST request with the Facebook profile object (along with another property I add in) to the ExpressJS server, which then saves it to MongoDB. The problem is, I haven't been able to get it to work. I'm wondering if I could modify the auth.login() function to instead return a promise, and take in a the extra parameter I need, and then subscribe to that from my component, and on success send the object. I've also tried to just put the POST request itself in the Auth Service constructor, but that hasn't worked. Here is my code so far:
home.html
...
<button class="btn btn-primary pull-left" type="submit" (click)="someFunction('extraProperty')">Submit</button>
...
home.component.ts
import { Component } from '#angular/core';
import { HomeService } from './home.service';
import { Auth } from './auth.service';
#Component({
moduleId: module.id,
selector: 'my-home',
templateUrl: 'home.html',
})
export class HomeComponent {
constructor(private homeService: HomeService, private auth: Auth) { }
someFunction(extraProperty: string): void {
// Saving extraProperty to local storage, then authenticating
localStorage.setItem('extraProperty', extraProperty);
this.auth.login();
}
}
home.service.ts
import { Injectable } from '#angular/core';
import {Observable} from 'rxjs/Rx';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Auth } from './auth.service';
#Injectable()
export class HomeService {
constructor (private http: Http) {}
private serverUrl = 'http://localhost:8000/';
// Trying to call this function after Auth Service login
postVote(body: Object): Observable<Boolean[]> {
return this.http.post((this.serverUrl + 'postVote'), body)
.map((res:Response) => {
console.log("Res is: ", res);
})
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
}
auth.service.ts
import { Injectable } from '#angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { HomeService } from './home.service';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import {Observable} from 'rxjs/Rx';
// Avoid name not found warnings
declare var Auth0Lock: any;
#Injectable()
export class Auth {
// Configure Auth0
lock = new Auth0Lock('CLIENT_ID', 'DOMAIN');
userProfile: any;
constructor(private homeService: HomeService, private http: Http) {
// Set userProfile attribute of already saved profile
this.userProfile = JSON.parse(localStorage.getItem('profile'));
// Add callback for lock `authenticated` event
this.lock.on("authenticated", (authResult) => {
localStorage.setItem('id_token', authResult.idToken);
// Fetch profile information
this.lock.getProfile(authResult.idToken, (error, profile) => {
if (error) {
// Handle error
alert(error);
return;
}
profile.extraProperty = localStorage.getItem('extraProperty');
localStorage.setItem('profile', JSON.stringify(profile));
this.userProfile = profile;
console.log(profile);
// Tried calling the service here, but I don't think it would work anyways in the constructor.
this.homeService.postVote(this.userProfile);
});
});
}
public login() {
// Call the show method to display the widget.
this.lock.show();
};
...
}
If I could also go about this in any other way that would be easier that you know of, that would be helpful as well. Essentially I'm trying to get the user's profile, save it to a DB in order to match them up with one person that holds the corresponding extraProperty, redirect to a new module and render the profile pic and name of the person with their match.
Thanks in advance!
Edit: Here is the function postVote on the server side. Hope that helps
// Adding vote object to MongoDB
router.post('/postVote', function(req, res, next) {
console.log("Req.body is: ", req.body);
Vote.save(function(err) {
if(err) {
throw err;
// return err;
}
console.log("Vote saved");
});
res.sendStatus(200);
});

Resources