1

I have a question about angular js 2. Who can talk to me how to receive data from input and return json string?

This's my code: http-test.component.ts

    <form action="POST">
        UserName 
        <div>
            <input type="text" required id= "username"/>
        </div>
        Password 
        <div>
            <input type="password" required id= "password" />
        </div>
        Name 
        <div>
            <input type="text" required id= "name"/>
        </div>
        <div>
            <button type ="submit"> Submit</button>
        </div>
    </form>
`,
styles:[`
    table tr:nth-child(even) {
    background-color: #eeeeee;
    }
`],
providers: [HttpTestService]

})

customers: Object;
constructor( private _httpService:HttpTestService){}
//Return Object json
onTestTable(){
    this._httpService.getCurrentTime()
        .subscribe(
        customers => this.customers = customers.records
        );

//On init when load page
ngOnInit(){
    this.onTestTable();
}

}

This's code Service: http-test.service.ts

constructor(private _http: Http) { }
getCurrentTime() {
    return this._http.get('http://www.w3schools.com/angular/customers.php')
            .map(res => res.json())
}
postJson(){
}

I want to receive data from input and return json string then post that json string to service when I press Submit. How can I do?

Thanks for reading!

1
  • 1
    Post some code snippet or more details about your question or what you have tried so far so that we can understand what is your problem exactly. Commented Jun 3, 2016 at 9:51

1 Answer 1

1

To receive data from an input, you could leverage the valueChanges property of control and build a JSON string in its associated callback with JSON.stringify():

@Component({
  (...)
  template: `
    <input [ngFormControl]="ctrl"/>
    {{jsonString}}
  `
})
export class SomeComponent {
  constructor() {
    this.ctrl = new Control();
    this.ctrl.valueChanges.subscribe((value) => {
      // receive the value

      // build the string string from the value
      // leveraging JSON.stringify()
      this.jsonString = (...)
    });
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.