POTD 5: Angular and backend PHP (using service and HTTP)

Due 10-June-2022, 1pm EST (no late submission, no extension)

Purpose:

For this exercise, you may work alone or with another student in this course.

Note: This option is somewhat similar to POTD 5 Angular HTTP where the standard Angular HTTP service is used to connect between the frontend and the backend.

For this option, you will implement your own service that utilizes Angular HTTP service. Your service may provide additional functionalities that are common and can be used by other modules or components through dependency injection.


Imagine you are writing an Angular app that will accept user's inputs. The Angular program will then send a request (i.e., asynchronous request) to a backend component. A backend component then processes the request and returns a response to the Angular program. The Angular program then uses the response and updates the screen.

You may use an Angular app you implemented for the Angular form and input validation activity as a starting point. Alternatively, you may create an Angular app from scratch or use an Angular part from your project to complete this activity. You will implement a PHP backend component that will accept a request from the Angular and return a response to the Angular.

A sample interface:
sample UI for angular form

A sample interface after receiving a response from the backend:
sample UI for angular form

You may modify your interface the way you like. Get creative. Feel free to add additional elements you feel should be included and have fun!


Tasks:

  1. Since the Angular app will interact with a backend PHP, HttpClient service is needed to handle requests and responses. HttpClient is part of HttpClientModule. Import HttpClientModule into the root module of the application (app.module.ts):
    import { HttpClientModule } from '@angular/common/http';
    Describe the dependency the root module has by including HttpClientModule in the imports array of the @ngModule declarator
  2. Assume that the app uses a data model to store and represent an order information. Create a class representing an order model
    • Create a class named order, using ng generate class class-name or ng g class class-name
    • Add properties to the class constructor such that the Order class can be used as a data model of the form (above)
      export class Order {
         constructor(
            public name: string,
            public email: string,
            public phone: number | null,
            public drink: string,
            public tempPreference: string,
            public sendText: boolean | null
         ){}
      }  
  3. Create a service named order. The order service will (i) provide streams of data that your app can subscribe to, and (ii) provide operations related to the drink orders (for example, process an order, send a request to a backend PHP to place an order, or add or modify an order). To create a service, use a terminal, and run the command: ng generate service service-name or ng g service service-name.

    Assume a service-name is order, running this command will produce in order.service.ts.

  4. Import the Order class into order.service.ts so that the service can use it as a data representation of a drink order.
    import { Order } from './order';
  5. Import HTTP-related classes into the order service (order.service.ts) so that it can use get() and post() methods provided by HttpClient service.
    import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
    • HttpClient — performs HTTP requests
    • HttpErrorResponse — represents an error or failure
    • HttpParams — represents parameters of an HTTP request/response
  6. Import Observable-related classes into the order service (order.service.ts) so that the service can utilize an observable (i.e., streams of data that your app can subscribe to).
    import { Observable, throwError } from 'rxjs';
  7. Inject the HttpClient dependency to manage the communication with the server in the constructor of the order service (order.service.ts)
    constructor(private http: HttpClient)
  8. Create a function named processOrder. This function takes the order information the customer places through an order form. You may decide how the order information will be processed prior to sending a request to the backend. It then calls a function named sendRequest, which sends the order information (i.e., a request) to a backend PHP. The function then returns an observable, allowing consumers (e.g., other components) to subscribe to.
  9. Create a function named sendRequest. This function interacts with a backend (i.e., sending a request and receiving a response). Use the get() method of the HttpClient to send a GET request. Alternatively, you may use the post() method of the HttpClient to send a POST request. The function then returns an observable, allowing consumers to subscribe to.
  10. Import the order service into the app component controller (app.component.ts)
    import { OrderService } from './order.service';
  11. Inject the order service into the app component controller (app.component.ts) through its constructor
    constructor(private orderService: OrderService)
  12. In the app component controller, implement a function named onSubmit that takes the form data and sends it to the order service for processing.

    The controller subscribes to and waits for the observable (returned by the order service) to emit the response. Use the subscribe() method so that the controller can use the emitted response to set the property, which will later be used to update the view of the app.

  13. In your PHP program, configure the header to instruct the server to give the Angular app the necessary privileges so that the request from the Angular app can be accepted by the server.
    // header('Access-Control-Allow-Origin: http://localhost:4200');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding');
    header('Access-Control-Max-Age: 1000');  
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
    Refer to dealing with CORS for more information on header setting for cross-site request.

    Write code to handle a GET (or POST) request

If you host your PHP program on GCP, you need to do the following extra steps.

Create a file named cors-json-file.json containing the following code (to force GCP PHP environment to accept remote request)

[ { "origin": ["*"], 
    "method": ["*"] } ]  

Use a terminal, run the following command
gsutil cors set cors-json-file.json gs://your-GCP-bucket


To deploy and test your Angular program, please refer to Angular deployment.

To deploy and test your PHP program use one of the following options:


You may modify your interface the way you like. Get creative. Feel free to add additional elements you feel should be included and have fun!

For more practice, try adding more content. Make use modules, components, classes, as well as data binding and directives.

Grading rubric

[Total: 10 points]: Done (or provide evidence of your attempt, full or reasonable effort)

Submission

Making your submission available to instructor and course staff is your responsibility; if we cannot access or open your file, you will not get credit. Be sure to test access to your file before the due date.



Copyright © 2022 Upsorn Praphamontripong

Released under the Creative Commons License CC-BY-NC-SA 4.0 license.

Last updated 2022-06-05 18:30