users: any = [];
runHttp(){
this.http.get('https://reqres.in/api/users?page=2').subscribe(data => {
console.log(data);
this.users = Object.values(data);
})
}
and html screen :
ion-button (click)="runHttp()" >User çek</ion-button>
<ion-list *ngFor='let user of users'>
<ion-item>
<h2>{{user.email}}</h2>
</ion-item>
</ion-list>
but h2{{user.email}} is empty in html screen why ?
Related
I'm very new in software project and currently working on final year project, mobile apps using ionic 3 framework. I have drag and drop function, first bucket with list of items and second bucket is empty. When I want to drag the items from 1st bucket to the 2nd bucket, I want to calculate the price for each entry at the second bucket but I really don't have idea to do it. Can someone help me with the codes :(
this is my calculate.ts
q1 = [];
q2 = [];
details: any = [];
totalPrice: number;
constructor(public navCtrl: NavController, private postPvdr: PostProvider, public navParams: NavParams, public dragulaService: DragulaService, public AlertController:AlertController) {
dragulaService.drop().subscribe((value) => {
console.log(value)
});
const bag: any = this.dragulaService.find('bag');
if (bag !== undefined ) this.dragulaService.destroy('bag');
this.dragulaService.createGroup('bag', {
revertOnSpill: true,
});
}
ionViewDidLoad() {
this.details = [];
this.getlist();
this.getTotalPrice()
}
getlist(){
let body = {
aksi: 'get_user'
};
this.postPvdr.postData(body, 'aksi_user.php').subscribe(data => {
for(let detail of data.result){
this.details.push(detail);
console.log(data);
}
});
}
getTotalPrice(){
let totalPrice = 0;
let body = {
aksi: 'get_user'
};
this.postPvdr.postData(body, 'aksi_user.php').subscribe(data => {
for(let detail of data.result){
totalPrice += Number.parseFloat(detail.dest_budget);
}
});
console.log(totalPrice);
return totalPrice;
}
these lines of codes seem weird because i just do try n error
this is my calculate.html
<ion-content padding>
<ion-row>
<ion-col width-50 class="left">
<div class="header">First Bucket</div>
<ion-list [dragula]='"bag"' [(dragulaModel)]="details">
<button ion-item *ngFor="let detail of details">
{{detail.dest_name}}
<p>{{ detail.dest_budget}}</p>
</button>
</ion-list>
</ion-col>
<ion-col width-50 class="right">
<div class="header">Second Bucket</div>
<ion-list [dragula]='"bag"' [(dragulaModel)]="q2">
<div ion-item *ngFor="let detail of q2">
{{detail.dest_name}}
<p>{{ detail.dest_budget }}</p>
</div>
</ion-list>
</ion-col>
</ion-row>
</ion-content>
<ion-footer>
<ion-toolbar>
<ion-title>Total Price:</ion-title>
</ion-toolbar>
</ion-footer>
the total price should be showing at the footer
here is my interface looks like
hope someone can help :)
call function here
dragulaService.drop().subscribe((value) => {
this.getTotalPrice();
});
modify the function
getTotalPrice(){
this.totalPrice = 0;
let body = {
aksi: 'get_user'
};
this.postPvdr.postData(body, 'aksi_user.php').subscribe(data => {
for(let detail of data.result){
this.totalPrice += Number.parseFloat(detail.dest_budget);
}
});
}
and bind model
<ion-footer>
<ion-toolbar>
<ion-title>Total Price:{{totalPrice}}</ion-title>
</ion-toolbar>
</ion-footer>
i want refresh app.component because in my sidemenu there is image and name so i store name and image in local storage but when i login and go to dashboard my app.component not refresh so need refresh app.components
My menu file
<ion-menu [content]="content">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<div class="profile">
<img class="profile-picture" src="assets/imgs/user_profile.png" />
<h3 class="name">{{name}}</h3>
</div>
<ion-list class="bg-color-menu" no-lines>
<ion-item menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
<ion-item>
<ion-avatar item-start>
<img [src]="p.icon" />
</ion-avatar>
{{p.title}}
</ion-item>
</ion-item>
</ion-list>
</ion-content>
</ion-menu>
<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
app.components
name:any;
this.name = localStorage.getItem("name");
Make your user data as BehaviorSubject.
Add a service - user.service.ts
export class UserService {
private currentUserSub = new BehaviorSubject<User>(null);
constructor(
private http: HttpClient
) {
const user = JSON.parse(localStorage.getItem('user'));
this.currentUserSub.next(user);
}
login(loginData): Observable<User> {
return this.http.post('login', loginData)
.map((res: any) => res.data)
.do((user: User) => {
localStorage.setItem('user', JSON.stringify(user));
this.currentUserSub.next(user);
});
}
getCurrentUserDetails(): Observable<User> {
const user = JSON.parse(localStorage.getItem('user'));
this.currentUserSub.next(user);
return this.currentUserSub;
}
}
call getCurrentUserDetails in app.component.ts to get the current user data
getUserDetails() {
this.userService.getCurrentUserDetails().subscribe(res => {
this.userProfile = res;
});
}
In app.html
<div class="profile">
<img class="profile-picture" src="userProfile.imgUrl" />
<h3 class="name">{{userProfile.name}}</h3>
</div>
this is an example. Do it as per your requirement.
I'm having a problem calling the data into the view. Console log is working as I included a screenshot.
ytapiUrl =https://www.googleapis.com/youtube/v3/playlistItems? part=snippet&playlistId='blahblahbla'
getECvideolists(){
return new Promise(resolve => {
this.httpClient.get(this.ytapiUrl).subscribe(ytdata => {
resolve(ytdata);
this.Ecvideos = ytdata;
console.log(ytdata);
}, err => {
console.log(err);
});
});
}
<ion-list *ngSwitchCase="'videos'">
<ion-item *ngFor="let Ecvideo of Ecvideos">
<h2> ***this doesn't display*** {{Ecvideo.items.snippet.title}}</h2>
</ion-item>
</ion-list>
[
items key has an array so you need to iterate it through *ngFor
for example,
<ion-list *ngSwitchCase="'videos'">
<ion-item *ngFor="let item of Ecvideos.items">
<h2>{{item.snippet.title}}</h2>
</ion-item>
</ion-list>
I have tried every solution but nothing has worked. I am building a chat app where i want it to be scrolled to last message automatically,also when new message comes it scrolls to the bottom.
I have tried scrollTo() on the #content but it doesn't work
chat.html
<ion-content #content *ngIf="buddy">
<div class = "chatwindow">
<ion-list no-lines *ngIf="allmessages">
<ion-item *ngFor = "let item of allmessages; let i = index" text-wrap>
<ion-avatar item-left *ngIf="item.sentby === buddy.uid">
<img src="{{buddy?.photoURL}}">
</ion-avatar>
<div class="bubble me" *ngIf="item.sentby === buddy.uid">
<h3 *ngIf="!imgornot[i]">{{item.message}}</h3>
<img src="{{item?.message}}" *ngIf="imgornot[i]">
</div>
<ion-avatar item-right *ngIf="item.sentby != buddy.uid">
<img src="{{photoURL}}">
</ion-avatar>
<div class="bubble you" *ngIf="item.sentby != buddy.uid">
<h3 *ngIf="!imgornot[i]">{{item.message}}</h3>
<img src="{{item?.message}}" *ngIf="imgornot[i]">
</div>
</ion-item>
</ion-list>
</div>
</ion-content>
chat.ts
#ViewChild('content') content: Content;
scrolltoBottom() {
setTimeout(() => {
// this.content.scrollToBottom();
}, 1000);
}
Your code should be like this.
export class ChatPage {
#ViewChild('content') content: Content;
constructor(public navCtrl: NavController) {
this.scrolltoBottom()
}
scrolltoBottom() {
setTimeout(() => {
this.content.scrollToBottom();
}, 300);
} }
I am building an Ionic 2 app and I am trying to use JWT to authenticate my users as shown here: https://auth0.com/blog/2016/02/18/ionic-2-authentication-how-to-secure-your-mobile-app-with-jwt/.
On clicking 'login' server sends back the token which I can see in my developer console network, however I get following error on console: (Error in build/pages/profile/profile.html:8:29 & ORIGINAL EXCEPTION: Error: JWT must have 3 parts.)Additionally I have to clear cookies everytime!
My profile.ts:
import {Page, Storage, LocalStorage} from 'ionic-angular';
import {Http, Headers} from '#angular/http';
import {FORM_DIRECTIVES} from '#angular/common';
import {JwtHelper} from 'angular2-jwt';
import {AuthService} from '../../services/auth/auth.service';
import 'rxjs/add/operator/map';
import { NavController, NavParams } from 'ionic-angular';
import { StartPage } from '../start/start.component';
#Page({
templateUrl: 'build/pages/profile/profile.html',
directives: [FORM_DIRECTIVES]
})
export class ProfilePage {
LOGIN_URL: string = " http://127.0.0.1:8000/rest-auth/login/";
SIGNUP_URL: string = "http://127.0.0.1:8000/rest-auth/registration/";
auth: AuthService;
// When the page loads, we want the Login segment to be selected
authType: string = "login";
// We need to set the content type for the server
contentHeader: Headers = new Headers({"Content-Type": "application/json"});
error: string;
jwtHelper: JwtHelper = new JwtHelper();
local: Storage = new Storage(LocalStorage);
user: string;
constructor(private http: Http, public nav:NavController) {
this.auth = AuthService;
this.local.get('profile').then(profile => {
this.user = JSON.parse(profile);
}).catch(error => {
console.log(error);
});
}
login(credentials) {
this.http.post(this.LOGIN_URL, JSON.stringify(credentials), { headers: this.contentHeader })
.map(res => res.json())
.subscribe(
data => this.authSuccess(data.id_token),
err => this.error = err
);
}
signup(credentials) {
this.http.post(this.SIGNUP_URL, JSON.stringify(credentials), { headers: this.contentHeader })
.map(res => res.json())
.subscribe(
data => this.authSuccess(data.id_token),
err => this.error = err
);
}
logout() {
this.local.remove('id_token');
this.user = null;
}
authSuccess(token) {
this.error = null;
this.local.set('id_token', token);
this.user = this.jwtHelper.decodeToken(token);
}
}
My service:
import {tokenNotExpired} from 'angular2-jwt';
export class AuthService {
constructor() {}
public static authenticated() {
return tokenNotExpired();
}
}
My profile.html:
<!-- app/profile/profile.html -->
<ion-navbar *navbar>
<button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Profile</ion-title>
</ion-navbar>
<ion-content class="login" *ngIf="!auth.authenticated()">
<div padding>
<ion-segment [(ngModel)]="authType">
<ion-segment-button value="login">
Login
</ion-segment-button>
<ion-segment-button value="signup">
Signup
</ion-segment-button>
</ion-segment>
</div>
<div [ngSwitch]="authType">
<form *ngSwitchWhen="'login'" #loginCreds="ngForm" (ngSubmit)="login(loginCreds.value)">
<ion-item>
<ion-label>Username</ion-label>
<ion-input type="text" ngControl="email"></ion-input>
</ion-item>
<ion-item>
<ion-label>Password</ion-label>
<ion-input type="password" ngControl="password"></ion-input>
</ion-item>
<div padding>
<button block type="submit">Login</button>
</div>
</form>
<form *ngSwitchWhen="'signup'" #signupCreds="ngForm" (ngSubmit)="signup(signupCreds.value)">
<ion-item>
<ion-label>Username</ion-label>
<ion-input type="text" ngControl="username"></ion-input>
</ion-item>
<ion-item>
<ion-label>Password</ion-label>
<ion-input type="password" ngControl="password"></ion-input>
</ion-item>
<div padding>
<button block type="submit">Signup</button>
</div>
</form>
</div>
<div padding>
<p *ngIf="error" class="error">{{ error._body }}</p>
</div>
</ion-content>
<ion-content>
<div *ngIf="auth.authenticated()">
<div padding>
<h1>Welcome, {{ user }}</h1>
<button block (click)="logout()">Logout</button>
</div>
</div>
</ion-content>
On successful login I would like to navigate to a specific page. What's going wrong and how can I fix this?
Also, the token I get back from my backend (I am using Django-rest-auth in my backend for authentication):