I'm working on a project in ionic 3,and am trying to do a login functionality in my app with php and mysql. but i got a problem reading data from json object to illustrate the situation, I have a table called "user" in my database, and I feched with php all the records and showed them as a json format like this:
<?php
header("Access-Control-Allow-Origin: *");
include ("cnx.php");
$query="select * from ionic_test ";
$result=$cnx->query($query);
$rs['user']=[];
while($record=$result->fetch(PDO::FETCH_ASSOC)){
$rs['user'][]=$record;
}
echo json_encode($rs);
I got this result:
{"user":[{"user":"abdel","pwd":"abdel"}]}
so,in my ionic project ,i have created a service which will connect to the php page and get the result shown above from it:
@Injectable()
export class AuthProvider {
private url:string
constructor(public http: HttpClient) {
this.url='http://localhost/ionic%20login/api.php'
}
getusers(){
return this.http.get(this.url)
}
now, whene I try to read the data returned by the httpClint request ,I got problems, I don't know actually how to get access to that data, I have tried many ways to read it but none of theme works for me,I always get "undefined" as a result :
constructor(public navCtrl: NavController,private authProvider:AuthProvider) {
}
ngOnInit(){
this.authProvider.getusers().subscribe(
(data)=>{
console.log(data);
},
error=>{
console.log(error);
}
)
}
the data which i want to read from the json object is this:
I hope that was clear enough to illustrate my problem,and i will be thankful if anyone can help me solve this problem .
Any suggestions or ways to do a login functionality with ionic 3 php and mysql is also appreciated.
You can tell HttpClient
the type of the response to make consuming the output easier and more obvious.
Typechecking of response can be done by using type parameter
export interface Response {
user: string;
pwd: string;
}
Http
returns an observable
and We can tell the HttpClient.get
to return response
as Response type When we use http.get<Response[]>(...)
then it returns the instance of Observable<Response[]>
type.
In your service
import { Observable } from 'rxjs/Observable';
import {Response} from './responseModel'
@Injectable()
export class AuthProvider {
private url:string
constructor(public http: HttpClient) {
this.url='http://localhost/ionic%20login/api.php'
}
getusers()Observable<Response[]>{
return this.http.get<Response[]>(this.url)
}
In your component subscribe to Observable<Response>
to get instance of Response
public response=[];
constructor(public navCtrl: NavController,private authProvider:AuthProvider) {
}
ngOnInit(){
this.authProvider.getusers().subscribe(
(data)=>{
this.response=data;
},
error=>{
console.log(error);
}
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.