1

I am trying to send a HTTP request from a form in Angular 2. I have the component class, the service class, and the HTML page. On the HTML page I have 2 forms, one for the GET request, another one for the Post request. The clicks successfully invoke the corresponding method in the service. The console log shows that URL is correct - url=http://localhost:8080/rentapp/policy. However, the request does not reach the server.

If I use the same HTML file without Angular 2 specifying the URL in the request is sent successfully. The link with the same URL also works for both Angular 2 and the HTML file.

So, the Component is create-policy.component.ts

@Component({
selector: 'app-create-policy',
providers: [CreatepolicyService],
templateUrl: './create-policy.component.html',
styleUrls: ['./create-policy.component.css']
})
export class CreatePolicyComponent implements OnInit {

policy = Object.assign(new Policy, {
id: 0,
title: "",
description: ""
});

constructor(private policyService: CreatepolicyService) { }

ngOnInit() {
}
onSubmitPostHttp() {
console.log("Started onSubmitPostHttp policy=" + this.policy);
this.policyService.addPolicyWithObservable(this.policy);
}
onSubmitGetHttp() {
console.log("Started onSubmitGettHttp policy=" + this.policy);
this.policyService.getPolicyWithObservable();
}
}

The HTML file is create-policy.component.html:

<div class="container">
                <form #f="ngForm" (ngSubmit)="onSubmitPostHttp()">
                    <p>
                        <label>Policy Title:</label> <input type="text" name="title"
                            [(ngModel)]="policy.title" required>
                    </p>
                    <p>
                        <label>Policy Description:</label> <input type="text"
                            name="description" [(ngModel)]="policy.description">
                    </p>
                    <p>
                        <button type="submit" [disabled]="!f.valid">Submit</button>
                    </p>
                </form>
                <form #f="ngForm" (ngSubmit)="onSubmitGetHttp()">
                    <p>
                        <button type="submit" [disabled]="!f.valid">Find Policies</button>
                    </p>
                </form>
                <a href="http://localhost:8080/rentapp/policy">PolicyGet</a>
            </div>

The service file is createpolicy.service.ts:

@Injectable()
export class CreatepolicyService {
url = "http://localhost:8080/rentapp/policy";
constructor(private http: Http) {}

public addPolicyWithObservable(policy: Policy): Observable<Policy> {
const headers = new Headers({'Content-Type': 'application/json'});
const options = new RequestOptions({headers: headers});
console.log("addPolicyWithObservable policy=" + policy + " url=" + this.url + " http=" + this.http);
return this.http.post(this.url, policy, options)
  .map(this.extractData)
  .catch(this.handleErrorObservable);
}

getPolicyWithObservable(): Observable<Policy[]> {
console.log("getPolicyWithObservable url=" + this.url);
    return this.http.get(this.url)
   .map(this.extractData)
   .catch(this.handleErrorObservable);
}

private extractData(res: Response) {
const body = res.json();
return body.data || {};
}
private handleErrorObservable(error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
}

The model file is policy.ts

export class Policy {
public id: number;
public title: string;
public description: string;

toString(): string {
return this.title + ': ' + this.description;
}
}
8
  • That probably won't do what you expect. In SPA, form actions result in page reload and are quite bad user experience. Instead read the form data in your code and make an HTTP request to the server yourself to pass the data. Commented Sep 11, 2017 at 15:42
  • @GünterZöchbauer that is what was originally, did not work either. I am correcting the question Commented Sep 11, 2017 at 15:51
  • "Originally I read the form data in my code and made an HTTP request to the server myself using the Http object but the result was the same, so I am showing the simplest code." It would be better to show this code. The code currently in your question doesn't make any sense with Angular. Commented Sep 11, 2017 at 15:56
  • @GünterZöchbauer, I corrected, please look Commented Sep 16, 2017 at 9:11
  • 1
    Observables are lazy. You need to call .subscribe(), otherwise nothing will happen. this.policyService.addPolicyWithObservable(this.policy).subsribe(); Commented Sep 16, 2017 at 9:38

2 Answers 2

1

Observables are lazy.
You need to call .subscribe(), otherwise nothing will happen.

this.policyService.addPolicyWithObservable(this.policy).subs‌​cribe();
Sign up to request clarification or add additional context in comments.

Comments

0

You need to write service for get data from API and return data to component and then you can use that data to display in you html.

Refer this link for more information.

1 Comment

thank you. I corrected the post and now I am showing the original code that follows the Angular standard - sending by an Http object. The result is the same

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.