Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add draft of guide #1

Merged
merged 1 commit into from
Apr 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
target/
.settings/
.project
.classpath
.factorypath
MANIFEST.MF
README.html
.DS_Store
ibm-web-ext.xml
**/webapp/app/
**/.vscode
**/node
22 changes: 22 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
language: java
before_script:
- unset _JAVA_OPTIONS
- cd finish
- chmod +x ../scripts/travisTest.sh
script: ../scripts/travisTest.sh
notifications:
slack:
template:
- 'Build: <%{build_url}| %{build_number}> | Commit (<%{compare_url}|%{commit}>):
%{commit_message}'
- 'Repo@Branch: %{repository_slug}@%{branch}'
- 'Author: %{author}'
- 'Summary: %{result} in %{duration}'
rooms:
secure: cVlTnHxyBuaqBaiQfqsyJrSuIYHMA/3Dpdh/0jbL5bITo0MmB6wVcJUTIA/8Nnzgi+cI83n13fGhGBrgefbhRCE+tZAdBPeqYxFbZkVg4JJ909dG8BBwS3N3gFtAGhh7gcZwN5fdc+2cGP4kF18uaViWIitGdmHe5p5XnZBuV0JBL1aXRfZOGbxerpBBEuWjIF7O2b69EWkKTb3nyZlctrSgmZeJWG0xZw7Fahbr7en9hpaemEatCsoiNAIN82CH26kiC3lOVzfGq+WZNabMtnd+ZP3AHnKapmoNB32rMLs3v8A5Nx+IPdwBbM1X0o5kjLgXrGwZhwfRkJ+MxPG8qvbCQNFtsXXhOE/PAFZ4nTn3oyWHRQbKJtYS6gzKGmMTF9BqDpoHsUm0isD/km23ainTc2eQOMgqdGMdzKVFO+4ze6BKhIHWO1VeZBTYkuTDN8S5J7BfMOYC4XhpQHaPvkES56zY2N0fek/AdL/aP5kaa0FwfxC3X/QRNQPe0XMd9MNZNCcOAPn1ieRLq25Lq+osm8we531QjUEU/i6PtPt8wyUzvtHW+oY9ckS67F2kBQ4gLzOckm2ekbnX9SHpd/Ze0BYIaSvFVQrVgKZFM3RvWTD6opGxv3FyRF08bqYT1tcEUPNibUqQ0Cs1ldgPkbcjuIjtArWPcPGzA6AmRtY=
on_success: never
on_failure: always
branches:
only:
- master
- qa
601 changes: 601 additions & 0 deletions LICENSE

Large diffs are not rendered by default.

274 changes: 274 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
// Copyright (c) 2019 IBM Corporation and others.
// Licensed under Creative Commons Attribution-NoDerivatives
// 4.0 International (CC BY-ND 4.0)
// https://creativecommons.org/licenses/by-nd/4.0/
//
// Contributors:
// IBM Corporation
:projectid: rest-client-angular
:page-layout: guide-multipane
:page-duration: 20 minutes
:page-description: Explore how to access a simple RESTful web service and consume its resources with Angular in Open Liberty.
:page-essential: false
:page-guide-catagory: none
:page-permalink: /guides/{projectid}
:page-releasedate: 2019-04-26
:page-related-guides: ['rest-intro', 'rest-client-java']
:page-seo-description: Find out how to consume a REST service with Angular on OpenLiberty
:page-seo-title: Consuming a REST service
:page-tags: ['Java EE']
:common-includes: https://raw.githubusercontent.com/OpenLiberty/guides-common/master
:source-highlighter: prettify
:guide-author: Open Liberty
= Consuming a RESTful web service with Angular

[.hidden]
NOTE: This repository contains the guide documentation source. To view the guide in published form,
view it on the https://openliberty.io/guides/{projectid}.html[Open Liberty website].

Explore how to access a simple RESTful web service and consume its resources with Angular in Open
Liberty.

// =================================================================================================
// Introduction
// =================================================================================================

== What you'll learn

You'll learn how to access a REST service and deserialize the returned JSON that contains a list of
artists and their albums by using an Angular service and the Angular HTTP Client. You'll present this
data using an Angular component.

The REST service that provides the artists and albums resource was written for you in advance and
responds with the [hotspot]`artists.json`.

https://angular.io[Angular^] is a framework for creating interactive web applications.
Angular applications are written in HTML, CSS, and
https://typescriptlang.org[TypeScript^], a variant of JavaScript.
Angular applications must be compiled. The Angular compilation step has been
configured as part of the Maven build.

The Angular application has been created and configured for you in the `frontend`
directory. It contains the default starter page.

artists.json
[source, json, linenums, role="code_column"]
----
include::finish/src/resources/artists.json[]
----

You will implement an Angular client that consumes this JSON and displays its contents at the
following URL: `\http://localhost:9080/app`.

To learn more about REST services and how you can write them, see
https://openliberty.io/guides/rest-intro.html[Creating a RESTful web service^].


// =================================================================================================
// Getting Started
// =================================================================================================
[role='command']
include::{common-includes}/gitclone.adoc[]


// =================================================================================================
// Starting the service
// =================================================================================================

== Starting the service

Before you begin the implementation, start the provided REST service so that
the artist JSON is available to you.

To start the REST service, navigate to the `start` directory and run the Maven
`install` and `liberty:start-server` goals:

[role='command']
----
mvn install liberty:start-server
----

After you start the server, you can find your artist JSON at
the following URL: http://localhost:9080/artists[http://localhost:9080/artists^].

You can rebuild the frontend at any time. To do so, run Maven with the
`generate-resources` goal:
[role='command']
----
mvn generate-resources
----

Any local changes to your TypeScript and HTML are picked up when you build the
frontend. After you start the Open Liberty server, you do not need to restart it.


// =================================================================================================
// Guide
// =================================================================================================

== Importing the HTTP client

Navigate to the start directory to begin.

Your application will need some way of communicating with RESTful web services in order
to retrieve their resources. In the case of this guide, your application will need to
communicate with the artists service to retrieve the artists JSON. While there are
a variety of ways of doing this, Angular contains a built-in HTTP Client module
that you can use.

Begin by importing the Angular HTTP Client module into your application module.

[role="code_command hotspot", subs="quotes"]
----
#Update the `app.module.ts` file.#
`src/main/frontend/src/app/app.module.ts`
----

app.module.ts
[source, javascript, linenums, role="code_column"]
----
include::finish/src/main/frontend/src/app/app.module.ts[tags=**]
----

Angular applications consist of modules; each module declares all other modules
that it imports or exports. AppModule is the root module, and most apps import
`HttpClientModule` here.

Import the [hotspot=3]`HttpClientModule` class and update the [hotspot=11-14]`imports`
array within the [hotspot=7-17]`@NgModule` declaration to include
[hotspot=13]`HttpClientModule`.

== Creating the Angular component

You will create the component in your application used to acquire and display data from
the REST API. This file will contain two classes: the service, which will handle data
access, and the component itself, which will handle presenting the data.The default
Angular application already contains a component.

[role="code_command hotspot", subs="quotes"]
----
#Update the `app.component.ts` file.#
`src/main/frontend/src/app/app.component.ts`
----

app.component.ts
[source, javascript, linenums, role="code_column"]
----
include::finish/src/main/frontend/src/app/app.component.ts[tags=**]
----

First, import two classes you'll need for the service: [hotspot=2]`HttpClient` and
[hotspot=3]`Injectable`.

Next, define the [hotspot=5-20]`ArtistsService` class. You can do this in a separate
file, or in the same file as the component. The class is annotated
[hotspot=5]`@Injectable` so instances can be provided to other classes
that need to use it.

The class injects an instance of the [hotspot=7]`HttpClient` class which it will use to
request data from the REST API. It contains a constant [hotspot=9]`ARTISTS_URL` which
points to the API endpoint it will request data from. Finally, it implements a method
[hotspot=11-18]`fetchArtists()` that makes the request and returns the result.

To obtain the data for display on the page, `fetchArtists()` Tries to use the
injected [hotspot=13]`http` instance to perform a `GET` HTTP request to the
[hotspot=9]`ARTISTS_URL` and returning the result. If an error occurs,it prints the
message of the error to the console.

[hotspot=11-18]`fetchArtists()` uses a feature of Javascript called
[hotspot=11]`async` and [hotspot=13]`await` to make the request and receive the
response without preventing the application from working while it waits. In order to be
compatible with this feature, the result of the [hotspot=13]`HttpClient.get()` method
must be converted to a Promise using `toPromise()`.

Finally, update the [hotspot=22-37]`AppComponent` class to use this service.

Add a [hotspot=25]`providers` property to the [hotspot=22-27]`@Component` annotation to
indicate that this component provides the [hotspot=5-18]`ArtistsService` to the rest of
the application.

Create a class member [hotspot=29]`artists` of type `any[]` and initialize it to an
empty array. This will hold the artists retrieved from the service so the template can
display them.

Inject an instance of the [hotspot=31]`ArtistsService` class into the constructor. In
[hotspot=33-37]`ngOnInit`, the method called when a component is ready to be displayed,
use the [hotspot=34]`artistsService` instance to request the artists data. Since
[hotspot=11-18]`fetchArtists()` is an `async` function, it will return a Promise. To
retrieve the data from the request, call [hotspot=34-36]`then()` on the promise and
provide a function that will take in the data and store it to the `artists` class
member.

== Creating the Angular component template

Now that you are fetching the data and storing it within your component, you will
display the data in the browser.

[role="code_command hotspot", subs="quotes"]
----
#Replace the template of your component.#
`src/main/frontend/src/app/app.component.html`
----

app.component.html
[source, html, linenums, role="code_column"]
----
include::finish/src/main/frontend/src/app/app.component.html[tags=html]
----

The Angular application is already set up to display the contents of this file. Replace
the Angular "Hello" HTML with a [hotspot=1]`div` that is repeated using `*ngFor` to
iterate over all artists. The `artists` variable is bound to the `artists` member of
the component. Use the same strategy to iterate over each [hotspot=3]`album` for the
artist.

After everything is set up, point your browser to the web application root
http://localhost:9080/app[http://localhost:9080/app^] to see the following output:

[subs="quotes", role="no_copy"]
----
foo wrote 2 albums:
Album titled *album_one* by *foo* contains *12* tracks
Album tilted *album_two* by *foo* contains *15* tracks
bar wrote 1 albums:
Album titled *foo walks into a bar* by *bar* contains *12* tracks
dj wrote 0 albums:
----


== Testing the Angular client

No explicit code directly uses the consumed artist JSON, so you do not need to write
any test cases for this guide.

Whenever you change and build your Angular implementation, the application root at
http://localhost:9080/app[http://localhost:9080/app^] will
reflect the changes automatically. You can visit the root to manually check whether
the artist JSON was consumed correctly. You can rebuild only your Angular frontend by
running the following command:
[role='command']
```
mvn generate-resources
```

When you are done checking the application root, stop the Open Liberty server by
running the following command:
[role='command']
```
mvn liberty:stop-server
```

Although this guide did not teach you how to build logic, you will likely build logic
when you develop your own applications, and testing will become a crucial part of your
development lifecycle. If you need to write test cases, follow the official unit
testing and end-to-end testing documentation on the
https://angular.io/guide/testing[official Angular page^].



== Great work! You're done!

You have just accessed a simple RESTful web service and consumed its resources using
Angular in Open Liberty.

include::{common-includes}/attribution.adoc[subs="attributes"]
1 change: 0 additions & 1 deletion README.md

This file was deleted.

Loading