NativeScript / nativescript-sdk-examples-ng

NativeScript and Angular code samples.
Apache License 2.0
291 stars 295 forks source link

HTTP Post not working #230

Closed madsongr closed 7 years ago

madsongr commented 7 years ago

I am trying to post data to my database but nothing is happening. I got no messages in console.log() or errors.

signup.ts

import { Component, ViewChild, ElementRef } from "@angular/core";
import { TNSCheckBoxModule } from 'nativescript-checkbox/angular';
import { Color } from "color";

import { MyHttpPostService } from '../../service';

@Component({
    selector: "signup",
    styleUrls: ['./components/signup/signup.css'],
    templateUrl: "./components/signup/signup.html",
    providers: [MyHttpPostService]
})

export class SignupComponent {

    public nome: string;
    public sobrenome: string;
    public cel: string;
    public end: string;
    public num: string;
    public bairro_: string;
    public cidade_: string;
    public cep_: string;
    public senha_: string;
    public confirmar_: string;
    public termos_: string;

    constructor(private post: MyHttpPostService){

    }

    myCheckColor = new Color("#f68533");

    public checkedChange(modelRef) {
        if(modelRef.checked === true){
            console.log("checkedChange:", modelRef.checked);
        }else {
            console.log("é false:", modelRef.checked);
        }
    }

    public cadastrar(){

        console.log(this.nome);
        this.post.postData({
            name: this.nome,
            uname: this.sobrenome,
            celular: this.cel,
            endereco: this.end,
            numero: this.num,
            bairro: this.bairro_,
            cidade: this.cidade_,
            cep: this.cep_,
            senha: this.senha_,
            confirmar: this.confirmar_,
            termos: this.termos_
        }).subscribe(res => {
            let resposta = res.json.data.NAME;
            console.log("res: "+res);
            console.log("res json: "+res.json);
            console.log("res json data: "+res.json.data);
            console.log("resposta: " + resposta);
        },
        err => {
          console.log("ERROR!: ", err);
        });
    }

}

service.ts

import { Injectable } from "@angular/core";
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Observable as RxObservable } from "rxjs/Observable";
import "rxjs/add/operator/map";

@Injectable()
export class MyHttpPostService {
    private serverUrl = "http://website.com/loginsystem/users/insert.php";

    constructor(private http: Http) { }

    postData(data: any) {
        let options = this.createRequestOptions();
        return this.http.post(this.serverUrl, { data }, options)
            .map(res => res.json());
    }

    private createRequestOptions() {
        let headers = new Headers();
        headers.append("Content-Type", "application/x-www-form-urlencoded");
        let options = new RequestOptions({ headers: headers });
        return options;
    }
}

app.module.ts

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NativeScriptFormsModule } from "nativescript-angular/forms";
import { AppRoutingModule } from "./app.routing";
import { AppComponent } from "./app.component";

import { TNSFontIconModule } from 'nativescript-ng2-fonticon';
import { TNSCheckBoxModule } from 'nativescript-checkbox/angular';

import { LoginComponent } from './components/login/login';
import { SignupComponent } from './components/signup/signup';

// Uncomment and add to NgModule imports if you need to use two-way binding
// import { NativeScriptFormsModule } from "nativescript-angular/forms";

// Uncomment and add to NgModule imports  if you need to use the HTTP wrapper
import { NativeScriptHttpModule } from "nativescript-angular/http";
import { MyHttpPostService } from './service';

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        AppRoutingModule,
        TNSCheckBoxModule,
        TNSFontIconModule.forRoot({
            'mdi': 'material-design-icons.css'
        }),
        NativeScriptHttpModule,
        NativeScriptFormsModule        
    ],
    declarations: [
        AppComponent,
        LoginComponent,
        SignupComponent
    ],
    providers: [
        MyHttpPostService
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
/*
Pass your application module to the bootstrapModule function located in main.ts to start your app
*/
export class AppModule { }
tsonevn commented 7 years ago

Hi @madsongr, I tested the HTTP module while using nativescript-sdl-examples-ng HTTP post example and everything seems to work as expected. Regarding that, the problem seems to be related to the backend service and the way it is handling the request.

Please verify, whether the request params are handled properly in the backend service.

madsongr commented 7 years ago

Thank you for your attention @tsonevn

My backend was good. I made some changes and it worked:

service.ts

import { Injectable } from "@angular/core";
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Observable as RxObservable } from "rxjs/Observable";
import "rxjs/add/operator/map";

let headers = new Headers(
    {
        'Content-Type': 'application/x-www-form-urlencoded'
    });

@Injectable()
export class MyHttpPostService {
    private serverUrl = "http://website.com/loginsystem/users/insert.php";

    constructor(private http: Http) { }

    postData(data: any) {
        return this.http.post(this.serverUrl, data, {headers:headers, method:"POST"}).map(res => res.json());
    }

}

signup.ts

import { Component, ViewChild, ElementRef } from "@angular/core";
import { TNSCheckBoxModule } from 'nativescript-checkbox/angular';
import { Color } from "color";
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Observable as RxObservable } from "rxjs/Observable";
import "rxjs/add/operator/map";

import { MyHttpPostService } from '../../service';

@Component({
    selector: "signup",
    styleUrls: ['./components/signup/signup.css'],
    templateUrl: "./components/signup/signup.html",
    providers: [MyHttpPostService]
})

export class SignupComponent {

    public message: string = ""

    constructor(private http: Http, private post: MyHttpPostService){

    }

    myCheckColor = new Color("#f68533");

    terms:any;

    public checkedChange(modelRef) {
        if(modelRef.checked === true){
            console.log("checkedChange:", modelRef.checked);
            this.terms = modelRef.checked;
        }else {
            console.log("é false:", modelRef.checked);
            this.terms = modelRef.checked;
        }        
    }

    userData = {"name": "", "uname": "", "celular": "", "endereco": "", "numero": "", "bairro": "",
    "cidade": "", "cep": "", "senha": "", "confirmar": "", "termos": this.terms}

    public cadastrar(){

        console.log(JSON.stringify(this.userData));

        this.post.postData(this.userData)
        .subscribe(res => {
            this.message = res[0].NOME;
            console.log(this.message);
        },
        err => {
          console.log("ERROR!: ", err);
        });

    }

}

signup.html:

<Page xmlns="http://schemas.nativescript.org/tns.xsd"
 xmlns:CheckBox="nativescript-checkbox"
 xmlns:RL="nativescript-ripple" class="page">

    <Page.actionBar>
        <ActionBar title="Cadastre-se" icon="" class="action-bar">
        </ActionBar>
    </Page.actionBar>

    <ScrollView>

        <StackLayout class="p-16">

            <Label text="Nome"></Label>
            <TextField text="" [(ngModel)]="userData.name" editable="true"></TextField>

            <Label text="Sobrenome"></Label>
            <TextField text="" [(ngModel)]="userData.uname" editable="true"></TextField>

            <Label text="Celular"></Label>
            <TextField text="" [(ngModel)]="userData.celular" editable="true"></TextField>

            <Label text="Endereço"></Label>
            <TextField text="" [(ngModel)]="userData.endereco" editable="true"></TextField>

            <Label text="Número"></Label>
            <TextField text="" [(ngModel)]="userData.numero" editable="true"></TextField>

            <Label text="Bairro"></Label>
            <TextField text="" [(ngModel)]="userData.bairro" editable="true"></TextField>

            <Label text="Cidade"></Label>
            <TextField text="" [(ngModel)]="userData.cidade" editable="true"></TextField>

            <Label text="Cep"></Label>
            <TextField text="" [(ngModel)]="userData.cep" editable="true"></TextField>

            <Label text="Senha"></Label>
            <TextField text="" [(ngModel)]="userData.senha" editable="true"></TextField>

            <Label text="Confirmar senha"></Label>
            <TextField text="" [(ngModel)]="userData.confirmar" editable="true"></TextField>

            <Label class="termos" text="Termos e condições" horizontalAlignment="center"></Label>

            <CheckBox #termos text="Li e aceito os termos e condições" 
            fillColor="{{ myCheckColor }}" checked="false" class="checkbox"
             (checkedChange)="checkedChange(termos)" [(ngModel)]="userData.termos" editable="true"></CheckBox>

            <RL:Ripple rippleColor="#df6107">
                <Button text="Cadastrar" (tap)="cadastrar()"></Button>
            </RL:Ripple>

        </StackLayout>

    </ScrollView>
</Page>
lock[bot] commented 5 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.