mirror of
https://github.com/angular/angular.git
synced 2026-09-14 13:54:52 +08:00
Compare commits
236 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 35690fdf6d | |||
| 3d7b8cdb4d | |||
| 2fff8fadbe | |||
| 0454158084 | |||
| 1575f9d8f3 | |||
| fc428f0443 | |||
| 9fa0ab5151 | |||
| 2a59e19886 | |||
| 4d8b164d3c | |||
| b13587c802 | |||
| 2f64981f7c | |||
| f02812d00e | |||
| f3907e1654 | |||
| 296459ac16 | |||
| 279e9e7fdb | |||
| 6a939562ea | |||
| b9e1e7e308 | |||
| 77eb4d8ecf | |||
| 48c946f8c9 | |||
| 81ad3c62d6 | |||
| cab701d0ee | |||
| 70ef08fc31 | |||
| 5a13eb8da0 | |||
| 3dc43e3577 | |||
| 9abe0d6d32 | |||
| c75fe04e28 | |||
| bce7f6bfd9 | |||
| edfc087998 | |||
| 1d4cf95a94 | |||
| 79a8b3c049 | |||
| fe20496554 | |||
| 461503be8e | |||
| 628c52055a | |||
| 0a9d1060b9 | |||
| 1017630d04 | |||
| 08ba49296a | |||
| aad9db2c5c | |||
| b6f119e182 | |||
| a6f2c03204 | |||
| a63d9a30d8 | |||
| 09a42d988e | |||
| 8235bc94f7 | |||
| f266a05d2f | |||
| 05a0225deb | |||
| 1d761bd7c7 | |||
| 2c140f4871 | |||
| a3de0c3cea | |||
| b0c1a90f55 | |||
| a40529af2e | |||
| ebd14e79fb | |||
| d1c83ccc02 | |||
| 108145020f | |||
| 702ec90110 | |||
| ffdfdc238f | |||
| e7dd72c8de | |||
| 9c07a42fbe | |||
| 9a37a7786a | |||
| da5f316ebf | |||
| cad7274ef9 | |||
| d9efa1b0d7 | |||
| c26e4bea9d | |||
| bd82fbeec4 | |||
| 1d32253ca6 | |||
| 6e1b3adadb | |||
| a6def648f5 | |||
| 9b61379096 | |||
| 08979e4589 | |||
| 233f33e6f1 | |||
| 35f491880c | |||
| 43e89bdacf | |||
| 07e78bbbf4 | |||
| e78a2a4a47 | |||
| 077f6b4674 | |||
| d201fc2dec | |||
| 6d6fc12c88 | |||
| 8ed4083a98 | |||
| 4c89a2497a | |||
| 0fecbabfd2 | |||
| ca5acadb78 | |||
| 978d37f324 | |||
| 656a38899a | |||
| 29c682ce5b | |||
| 3f8e4fb724 | |||
| c3cff35869 | |||
| a844435514 | |||
| 901353ec7a | |||
| 288156b06b | |||
| bf4d856834 | |||
| 3bb76768a6 | |||
| be2db59a55 | |||
| 9c57b656a1 | |||
| b293c6a77c | |||
| 951a3474d6 | |||
| b5e68e42c1 | |||
| a404587615 | |||
| 6c9886b1ca | |||
| 3c75f98117 | |||
| cd5d7b6615 | |||
| 97d58ec091 | |||
| 087f4412af | |||
| 0f0c0a9452 | |||
| bae6b5ceb1 | |||
| 868dcabdee | |||
| 8f6cbb66a2 | |||
| c807a324d1 | |||
| 2e37e2365b | |||
| bb2753decb | |||
| e6736c77a0 | |||
| 3d71d9ddd9 | |||
| c9816448ed | |||
| 589e76b7ef | |||
| bba3fcb30b | |||
| 6f139b4f0b | |||
| dfa7f648d6 | |||
| 5a3d121204 | |||
| e4516c75d2 | |||
| 32e98f7937 | |||
| 6c189ed0f1 | |||
| 2df92f7633 | |||
| 1535ab90da | |||
| c2726650f6 | |||
| a44224ce59 | |||
| 3c71e4846a | |||
| 43dff1fc27 | |||
| 7e23883b5d | |||
| 7efaf525a5 | |||
| f099df839e | |||
| c9e8804b5c | |||
| 2dee505582 | |||
| 75d5bfda1e | |||
| 993750815e | |||
| 88a0ff74ad | |||
| 75b2a265a9 | |||
| d0a73b24fe | |||
| e0be553abf | |||
| ffccb8e3a7 | |||
| b13e079bc7 | |||
| 84f45363eb | |||
| 980147555c | |||
| 182258520d | |||
| ac59054cd4 | |||
| b90b3299aa | |||
| 4ae753d84f | |||
| f859de3e60 | |||
| 5bb4407c01 | |||
| 5e85c138fa | |||
| b23fa5e977 | |||
| 05db4797e8 | |||
| 6b9ec0b830 | |||
| b0a9e67419 | |||
| f321e65c46 | |||
| 13e675ea87 | |||
| de48c99afb | |||
| 81e32f4283 | |||
| e20b6d98d9 | |||
| d42032a380 | |||
| ffc684381f | |||
| 8f7fbddb51 | |||
| bca3aed9e4 | |||
| 819b9f32b4 | |||
| 6207d6f1f0 | |||
| 174997150f | |||
| 439b4d3a89 | |||
| 377d0c9c1e | |||
| d60ea6ab5a | |||
| dafb765926 | |||
| 44d095a61c | |||
| 600fd12fda | |||
| d100ddfd6e | |||
| 1aadabb508 | |||
| d252187c45 | |||
| 6d6b76c59f | |||
| 5f2822ce1f | |||
| acc87a41ce | |||
| 7eec66c449 | |||
| 8fc02f56d0 | |||
| 313760b851 | |||
| 87252dcbbc | |||
| 785ab81a7b | |||
| 19a4cdec7d | |||
| 3062442728 | |||
| 138b4936b7 | |||
| af31adb8dd | |||
| f0e926074d | |||
| 7ec76dea5f | |||
| a852862ff9 | |||
| 6107d2ebbc | |||
| 56f7d1f61a | |||
| 6d912960b9 | |||
| 8542593c80 | |||
| d0fa598fe4 | |||
| 04d8b6c61a | |||
| 92b0bda9e4 | |||
| d7835e4f1a | |||
| e384c69b83 | |||
| aa10532458 | |||
| 7677963bd9 | |||
| 03fcb36cfd | |||
| 2f0856070b | |||
| 7b4d3c036d | |||
| c98c6a8452 | |||
| 630193543f | |||
| cff84d00cf | |||
| ba7a757cc5 | |||
| ecb309152f | |||
| 2fd81940d3 | |||
| 0950ef6a49 | |||
| e69ba26c55 | |||
| 61878883ed | |||
| 8ed653b93f | |||
| b76b176733 | |||
| f8a932afbb | |||
| d784986cd3 | |||
| 31a71a0f89 | |||
| 3d8efece03 | |||
| 345817f427 | |||
| 24b6eea0a9 | |||
| d457ffc408 | |||
| a378267117 | |||
| 11f8f8d8e4 | |||
| 4811850607 | |||
| 5d6440947a | |||
| 25e220a23a | |||
| c95766ed12 | |||
| 43e9301783 | |||
| e63fb8031a | |||
| 25bed17c5f | |||
| 117af7d8b5 | |||
| ee7a9248a8 | |||
| e1607cdbd4 | |||
| b06a1d0349 | |||
| a814ed1382 | |||
| 1a7444f99f | |||
| bf4ad38117 | |||
| 86d4016d23 | |||
| 440b51b7af |
@@ -134,9 +134,10 @@ build:remote --project_id=internal-200822
|
||||
build:remote --remote_cache=remotebuildexecution.googleapis.com
|
||||
build:remote --remote_executor=remotebuildexecution.googleapis.com
|
||||
|
||||
# Ensure that tags like "no-remote-exec" get propagated to actions created by rules.
|
||||
# Ensure that tags like "no-remote-exec" get propagated to actions created by rules,
|
||||
# even if the rule implementation does not explicitly pass them to the execution requirements.
|
||||
# https://bazel.build/reference/command-line-reference#flag--experimental_allow_tags_propagation
|
||||
build --experimental_allow_tags_propagation
|
||||
common --experimental_allow_tags_propagation
|
||||
|
||||
# Disable network access in the sandbox by default. To enable network access
|
||||
# for a particular target, use:
|
||||
|
||||
+15
-13
@@ -74,7 +74,7 @@ var_9: &only_release_branches
|
||||
# https://circleci.com/developer/orbs.
|
||||
orbs:
|
||||
node: circleci/node@5.0.1
|
||||
devinfra: angular/dev-infra@1.0.6
|
||||
devinfra: angular/dev-infra@1.0.8
|
||||
|
||||
# Executor Definitions
|
||||
# https://circleci.com/docs/2.0/reusing-config/#authoring-reusable-executors
|
||||
@@ -89,7 +89,7 @@ executors:
|
||||
type: string
|
||||
default: medium
|
||||
docker:
|
||||
- image: cimg/node:16.13.0
|
||||
- image: cimg/node:16.14.0
|
||||
resource_class: << parameters.resource_class >>
|
||||
working_directory: ~/ng
|
||||
|
||||
@@ -99,7 +99,7 @@ executors:
|
||||
type: string
|
||||
default: medium
|
||||
docker:
|
||||
- image: cimg/node:16.13.0-browsers
|
||||
- image: cimg/node:16.14.0-browsers
|
||||
resource_class: << parameters.resource_class >>
|
||||
working_directory: ~/ng
|
||||
|
||||
@@ -150,7 +150,7 @@ commands:
|
||||
name: Configure git
|
||||
command: |
|
||||
mkdir -p ~/.ssh
|
||||
echo 'github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==' >> ~/.ssh/known_hosts
|
||||
echo 'github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=' >> ~/.ssh/known_hosts
|
||||
git config --global url."ssh://git@github.com".insteadOf "https://github.com" || true
|
||||
git config --global gc.auto 0 || true
|
||||
|
||||
@@ -595,22 +595,16 @@ jobs:
|
||||
executor: windows-executor
|
||||
steps:
|
||||
- checkout
|
||||
- save_month_to_file
|
||||
- capture_patches_for_cache_key
|
||||
- init_environment
|
||||
|
||||
# Setup the proper NodeJS version. The image comes pre-installed with `nvm-windows`.
|
||||
# Note: This happens immediately after checkout because environment initialization logic
|
||||
# might rely on Node and shouldn't use the older image-provided NodeJS version.
|
||||
- run:
|
||||
name: Install NodeJS version from `.nvmrc`.
|
||||
command: |
|
||||
nvm on
|
||||
nvm install $(cat .nvmrc)
|
||||
nvm use $(cat .nvmrc)
|
||||
|
||||
- restore_cache:
|
||||
keys:
|
||||
- *cache_key_win
|
||||
- *cache_key_win_fallback
|
||||
|
||||
- run:
|
||||
name: Debug information for flakiness of Windows job
|
||||
command: |
|
||||
@@ -621,6 +615,14 @@ jobs:
|
||||
echo "Path: $PATH"
|
||||
yarn node -v
|
||||
|
||||
- save_month_to_file
|
||||
- capture_patches_for_cache_key
|
||||
- init_environment
|
||||
- restore_cache:
|
||||
keys:
|
||||
- *cache_key_win
|
||||
- *cache_key_win_fallback
|
||||
|
||||
# Install project dependencies, and install Bazelisk globally. This is necessary as
|
||||
# Windows might error when `bazel` is invoked from the project node modules. The Bazel
|
||||
# invocation might modify the symlinked project `node_modules` again, causing failures.
|
||||
|
||||
@@ -4,7 +4,7 @@ description: 'Installs the dependencies using Yarn'
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- uses: actions/cache@6998d139ddd3e68c71e9e398d8e40b71a2f39812 # v3
|
||||
- uses: actions/cache@88522ab9f39a2ea568f7027eddc7d8d8bc9d59c8 # v3
|
||||
with:
|
||||
path: |
|
||||
./node_modules/
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Configuration for angular-robot
|
||||
|
||||
#options for the size plugin
|
||||
# options for the size plugin
|
||||
size:
|
||||
disabled: false
|
||||
disabled: true
|
||||
maxSizeIncrease: 2000
|
||||
circleCiStatusName: 'ci/circleci: test'
|
||||
|
||||
@@ -70,7 +70,6 @@ merge:
|
||||
requiredStatuses:
|
||||
- 'ci/circleci: build'
|
||||
- 'ci/circleci: lint'
|
||||
- 'ci/angular: size'
|
||||
- 'google-internal-tests'
|
||||
- 'pullapprove'
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
||||
- uses: ./.github/actions/yarn-install
|
||||
|
||||
- uses: angular/dev-infra/github-actions/setup-bazel-remote-exec@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: angular/dev-infra/github-actions/setup-bazel-remote-exec@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
bazelrc: ./.bazelrc.user
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
# the number of concurrent actions is determined based on the host resources.
|
||||
- run: bazel build //aio:build --jobs=32 --announce_rc --verbose_failures
|
||||
|
||||
- uses: angular/dev-infra/github-actions/deploy-previews/pack-and-upload-artifact@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: angular/dev-infra/github-actions/deploy-previews/pack-and-upload-artifact@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
workflow-artifact-name: 'aio'
|
||||
pull-number: '${{github.event.pull_request.number}}'
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||
steps:
|
||||
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # tag=v3
|
||||
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3
|
||||
|
||||
- name: Configure Firebase deploy target
|
||||
working-directory: aio/
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
npx -y firebase-tools@latest target:clear --project ${{env.PREVIEW_PROJECT}} hosting aio
|
||||
npx -y firebase-tools@latest target:apply --project ${{env.PREVIEW_PROJECT}} hosting aio ${{env.PREVIEW_SITE}}
|
||||
|
||||
- uses: angular/dev-infra/github-actions/deploy-previews/upload-artifacts-to-firebase@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: angular/dev-infra/github-actions/deploy-previews/upload-artifacts-to-firebase@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
github-token: '${{secrets.GITHUB_TOKEN}}'
|
||||
workflow-artifact-name: 'aio'
|
||||
|
||||
@@ -16,6 +16,6 @@ jobs:
|
||||
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: angular/dev-infra/github-actions/branch-manager@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: angular/dev-infra/github-actions/branch-manager@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
|
||||
|
||||
@@ -12,14 +12,14 @@ jobs:
|
||||
labels:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
||||
- uses: angular/dev-infra/github-actions/commit-message-based-labels@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
|
||||
- uses: angular/dev-infra/github-actions/commit-message-based-labels@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
|
||||
post_approval_changes:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
||||
- uses: angular/dev-infra/github-actions/post-approval-changes@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
|
||||
- uses: angular/dev-infra/github-actions/post-approval-changes@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
|
||||
|
||||
@@ -14,6 +14,6 @@ jobs:
|
||||
if: github.repository == 'angular/angular'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: angular/dev-infra/github-actions/feature-request@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: angular/dev-infra/github-actions/feature-request@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
|
||||
|
||||
@@ -12,8 +12,8 @@ jobs:
|
||||
trigger:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
||||
- uses: angular/dev-infra/github-actions/google-internal-tests@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
|
||||
- uses: angular/dev-infra/github-actions/google-internal-tests@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
run-tests-guide-url: http://go/angular/g3sync
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -14,6 +14,6 @@ jobs:
|
||||
if: github.repository == 'angular/angular'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: angular/dev-infra/github-actions/lock-closed@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: angular/dev-infra/github-actions/lock-closed@462f716ef571b2b41fff90aaa5bb10897693efcc
|
||||
with:
|
||||
lock-bot-key: ${{ secrets.LOCK_BOT_PRIVATE_KEY }}
|
||||
|
||||
@@ -9,6 +9,6 @@ jobs:
|
||||
status:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: angular/dev-infra/github-actions/unified-status-check@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
- uses: angular/dev-infra/github-actions/unified-status-check@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
|
||||
|
||||
@@ -25,12 +25,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: 'Checkout code'
|
||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
||||
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: 'Run analysis'
|
||||
uses: ossf/scorecard-action@e38b1902ae4f44df626f11ba0734b14fb91f8f86 # v2.1.2
|
||||
uses: ossf/scorecard-action@80e868c13c90f172d68d1f4501dee99e2479f7af # v2.1.3
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
@@ -47,6 +47,6 @@ jobs:
|
||||
|
||||
# Upload the results to GitHub's code scanning dashboard.
|
||||
- name: 'Upload to code-scanning'
|
||||
uses: github/codeql-action/upload-sarif@17573ee1cc1b9d061760f3a006fc4aac4f944fd5 # v2.2.4
|
||||
uses: github/codeql-action/upload-sarif@7df0ce34898d659f95c0c4a09eaa8d4e32ee64db # v2.2.12
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
env:
|
||||
ANGULAR_CLI_BUILDS_READONLY_GITHUB_TOKEN: ${{ secrets.ANGULAR_CLI_BUILDS_READONLY_GITHUB_TOKEN }}
|
||||
- name: Create a PR (if necessary)
|
||||
uses: angular/dev-infra/github-actions/create-pr-for-changes@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
uses: angular/dev-infra/github-actions/create-pr-for-changes@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
branch-prefix: update-cli-help
|
||||
pr-title: 'docs: update Angular CLI help [${{github.ref_name}}]'
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
- name: Generate `events.json`
|
||||
run: node aio/scripts/generate-events/index.mjs --ignore-invalid-dates
|
||||
- name: Create a PR (if necessary)
|
||||
uses: angular/dev-infra/github-actions/create-pr-for-changes@accc3c96df0d40ff639070132acb0699a58bfcf8
|
||||
uses: angular/dev-infra/github-actions/create-pr-for-changes@1564c4e45db49460f2351cba356311e28062aa2f
|
||||
with:
|
||||
branch-prefix: docs-update-events
|
||||
pr-title: 'docs: update events'
|
||||
|
||||
@@ -14,7 +14,7 @@ export const caretaker: CaretakerConfig = {
|
||||
},
|
||||
{
|
||||
name: 'Initial Triage Queue',
|
||||
query: `is:open no:milestone`,
|
||||
query: `is:open no:milestone -draft:true`,
|
||||
},
|
||||
],
|
||||
caretakerGroup: 'angular-caretaker',
|
||||
|
||||
+6
-2
@@ -56,8 +56,9 @@
|
||||
|
||||
version: 3
|
||||
|
||||
# availability:
|
||||
# users_unavailable:
|
||||
availability:
|
||||
users_unavailable:
|
||||
- devversion
|
||||
|
||||
# Meta field that goes unused by PullApprove to allow for defining aliases to be
|
||||
# used throughout the config.
|
||||
@@ -350,6 +351,7 @@ groups:
|
||||
'aio/content/guide/singleton-services.md',
|
||||
'aio/content/guide/sharing-ngmodules.md',
|
||||
'aio/content/guide/standalone-components.md',
|
||||
'aio/content/guide/standalone-migration.md',
|
||||
'aio/content/guide/structural-directives.md',
|
||||
'aio/content/examples/structural-directives/**/{*,.*}',
|
||||
'aio/content/guide/svg-in-templates.md',
|
||||
@@ -416,6 +418,7 @@ groups:
|
||||
'aio/content/guide/http-request-data-from-server.md',
|
||||
'aio/content/guide/http-security-xsrf-protection.md',
|
||||
'aio/content/guide/http-send-data-to-server.md',
|
||||
'aio/content/guide/http-server-communication.md',
|
||||
'aio/content/guide/http-setup-server-communication.md',
|
||||
'aio/content/guide/http-test-requests.md',
|
||||
'aio/content/guide/http-track-show-request-progress.md',
|
||||
@@ -952,6 +955,7 @@ groups:
|
||||
'aio/content/guide/migration-module-with-providers.md',
|
||||
'aio/content/guide/static-query-migration.md',
|
||||
'aio/content/guide/update-to-latest-version.md',
|
||||
'aio/content/guide/versions.md',
|
||||
'aio/content/guide/update-to-version-14.md',
|
||||
'aio/content/guide/update-to-version-15.md'
|
||||
])
|
||||
|
||||
+190
-117
@@ -1,16 +1,149 @@
|
||||
<a name="15.1.5"></a>
|
||||
# 15.1.5 (2023-02-15)
|
||||
### forms
|
||||
<a name="15.2.8"></a>
|
||||
# 15.2.8 (2023-04-19)
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [5f2a3edcf2](https://github.com/angular/angular/commit/5f2a3edcf27cfe6ffc6ae4d67ca2b47953f26336) | fix | Make radio buttons respect `[attr.disabled]` ([#48864](https://github.com/angular/angular/pull/48864)) |
|
||||
## Special Thanks
|
||||
AleksanderBodurri, Alvaro Junqueira, Dylan Hunn, Joey Perrott, Matthieu Riegler, PaloMiklo and Paul Gschwendtner
|
||||
| [2fff8fadbe](https://github.com/angular/angular/commit/2fff8fadbeff9df3bc09b8847dbf08febbe3b5f8) | fix | handle invalid classes in class array bindings ([#49924](https://github.com/angular/angular/pull/49924)) |
|
||||
### http
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [05a0225deb](https://github.com/angular/angular/commit/05a0225deb126849f3798e828f6dbef7c221ec57) | fix | prevent headers from throwing an error when initializing numerical values ([#49379](https://github.com/angular/angular/pull/49379)) |
|
||||
### router
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [09a42d988e](https://github.com/angular/angular/commit/09a42d988e654825648205c8df90f7ca4d034c74) | fix | canceledNavigationResolution: 'computed' with redirects to the current URL ([#49793](https://github.com/angular/angular/pull/49793)) |
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.0-next.4"></a>
|
||||
# 15.2.0-next.4 (2023-02-08)
|
||||
<a name="15.2.7"></a>
|
||||
# 15.2.7 (2023-04-12)
|
||||
### compiler
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [b0c1a90f55](https://github.com/angular/angular/commit/b0c1a90f55ecfafb4fd5c22cdd1b4a5f12573f22) | fix | Produce diagnositc if directive used in host binding is not exported ([#49792](https://github.com/angular/angular/pull/49792)) |
|
||||
### compiler-cli
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [a40529af2e](https://github.com/angular/angular/commit/a40529af2e2923f1dbdae8898a0e94e9e63a3fcf) | fix | Catch FatalDiagnosticError during template type checking ([#49792](https://github.com/angular/angular/pull/49792)) |
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [702ec90110](https://github.com/angular/angular/commit/702ec901100b2d84efdf0b16d8347f8b28b94d5d) | fix | When using setInput, mark view dirty in same way as `markForCheck` ([#49747](https://github.com/angular/angular/pull/49747)) |
|
||||
## Special Thanks
|
||||
Alan Agius, Andrew Kushnir, Andrew Scott, Kristiyan Kostadinov, Matthieu Riegler and Nikola Kološnjaji
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.6"></a>
|
||||
# 15.2.6 (2023-04-05)
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [d9efa1b0d7](https://github.com/angular/angular/commit/d9efa1b0d742217de1164f7904c202b2697348d9) | feat | change the URL sanitization to only block javascript: URLs ([#49659](https://github.com/angular/angular/pull/49659)) |
|
||||
### router
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [cad7274ef9](https://github.com/angular/angular/commit/cad7274ef90914f0c24d071473a6cbae0e5b8250) | fix | create correct URL relative to path with empty child ([#49691](https://github.com/angular/angular/pull/49691)) |
|
||||
| [9b61379096](https://github.com/angular/angular/commit/9b6137909690d6cbfdd8cbef502e9e2ac0d28c4a) | fix | Ensure initial navigation clears current navigation when blocking ([#49572](https://github.com/angular/angular/pull/49572)) |
|
||||
## Special Thanks
|
||||
Andrew Scott, Guillaume Weghsteen, John Manners, Johnny Gérard, Matthieu Riegler, Robin Richtsfeld, Sandra Limacher, Sarthak Thakkar, Vinit Neogi and vikram menon
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.5"></a>
|
||||
# 15.2.5 (2023-03-29)
|
||||
### common
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [ca5acadb78](https://github.com/angular/angular/commit/ca5acadb78c33bf896001a5810cb4be15ff7bc86) | fix | invalid ImageKit transformation ([#49201](https://github.com/angular/angular/pull/49201)) |
|
||||
### compiler
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [077f6b4674](https://github.com/angular/angular/commit/077f6b4674c01bfed083e73a17d848e226e543b4) | fix | do not unquote CSS values ([#49460](https://github.com/angular/angular/pull/49460)) |
|
||||
| [c3cff35869](https://github.com/angular/angular/commit/c3cff35869648fdf70c9707c3d87bcfdcc84d903) | fix | handle trailing comma in object literal ([#49535](https://github.com/angular/angular/pull/49535)) |
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [d201fc2dec](https://github.com/angular/angular/commit/d201fc2dec1a3a9cc6952ebb46cb672200a78236) | fix | set style property value to empty string instead of an invalid value ([#49460](https://github.com/angular/angular/pull/49460)) |
|
||||
### router
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [978d37f324](https://github.com/angular/angular/commit/978d37f324ce4a1fe9b57f3d9430d7c28ecf6131) | fix | Ensure Router preloading works with lazy component and static children ([#49571](https://github.com/angular/angular/pull/49571)) |
|
||||
| [a844435514](https://github.com/angular/angular/commit/a844435514962c52f4fb480bcfab7ee6519a59cc) | fix | fix [#49457](https://github.com/angular/angular/pull/49457) outlet activating with old info ([#49459](https://github.com/angular/angular/pull/49459)) |
|
||||
## Special Thanks
|
||||
Alan Agius, Andrew Scott, Asaf Malin, Jan Cabadaj, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Sid and Tano Abeleyra
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.4"></a>
|
||||
# 15.2.4 (2023-03-22)
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [bae6b5ceb1](https://github.com/angular/angular/commit/bae6b5ceb16bd87c8146aa29564a8d29135a6f95) | fix | Allow `TestBed.configureTestingModule` to work with recursive cycle of standalone components. ([#49473](https://github.com/angular/angular/pull/49473)) |
|
||||
| [087f4412af](https://github.com/angular/angular/commit/087f4412afe9ccdefe7d63012af749b79f3e84d0) | fix | more accurate matching of classes during content projection ([#48888](https://github.com/angular/angular/pull/48888)) |
|
||||
## Special Thanks
|
||||
Aditya Srinivasan, Alex Rickabaugh, Andrew Scott, Kristiyan Kostadinov, Masaoki Kobayashi, Matthieu Riegler, Paul Gschwendtner, Peter Götz, Thomas Pischke, Virginia Dooley and avmaxim
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.3"></a>
|
||||
# 15.2.3 (2023-03-16)
|
||||
## Special Thanks
|
||||
Alan Agius, Esteban Gehring, Matthieu Riegler and Virginia Dooley
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.2"></a>
|
||||
# 15.2.2 (2023-03-08)
|
||||
### migrations
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [6207d6f1f0](https://github.com/angular/angular/commit/6207d6f1f0771ff3b74379367e65af665ef0e51c) | fix | add protractor support if protractor imports are detected ([#49274](https://github.com/angular/angular/pull/49274)) |
|
||||
## Special Thanks
|
||||
Alan Agius, Andrew Kushnir, Andrew Scott, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Sai Kartheek Bommisetty and Vinit Neogi
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.1"></a>
|
||||
# 15.2.1 (2023-03-01)
|
||||
### common
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [f0e926074d](https://github.com/angular/angular/commit/f0e926074df189b3e3ca361a6a3bcd852c05e010) | fix | make Location.normalize() return the correct path when the base path contains characters that interfere with regex syntax. ([#49181](https://github.com/angular/angular/pull/49181)) |
|
||||
### compiler-cli
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [04d8b6c61a](https://github.com/angular/angular/commit/04d8b6c61a0d0a2d61b9202d09774f3ab347e82f) | fix | do not persist component analysis if template/styles are missing ([#49184](https://github.com/angular/angular/pull/49184)) |
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [d60ea6ab5a](https://github.com/angular/angular/commit/d60ea6ab5a22cb4f3677e34d0d7f6be0c3fe23fe) | fix | update zone.js peerDependencies ranges ([#49244](https://github.com/angular/angular/pull/49244)) |
|
||||
### migrations
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [44d095a61c](https://github.com/angular/angular/commit/44d095a61cb340ea1f5e0a19370ea839378b02c3) | fix | avoid migrating the same class multiple times in standalone migration ([#49245](https://github.com/angular/angular/pull/49245)) |
|
||||
| [92b0bda9e4](https://github.com/angular/angular/commit/92b0bda9e4e7117552f929bf86acfc0ae65779a1) | fix | delete barrel exports in standalone migration ([#49176](https://github.com/angular/angular/pull/49176)) |
|
||||
### router
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [3062442728](https://github.com/angular/angular/commit/30624427289ad65bdbabd865d028146753c3a97a) | fix | add error message when using loadComponent with a NgModule ([#49164](https://github.com/angular/angular/pull/49164)) |
|
||||
## Special Thanks
|
||||
Alan Agius, Andrew Kushnir, Aristeidis Bampakos, Craig Spence, Doug Parker, Iván Navarro, Joey Perrott, Kristiyan Kostadinov, Matthieu Riegler, Michael Ziluck, Paul Gschwendtner, Stephanie Tuerk, Vincent and Virginia Dooley
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.0"></a>
|
||||
# 15.2.0 (2023-02-22)
|
||||
## Deprecations
|
||||
###
|
||||
- Class and `InjectionToken` guards and resolvers are
|
||||
deprecated. Instead, write guards as plain JavaScript functions and
|
||||
inject dependencies with `inject` from `@angular/core`.
|
||||
###
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [926c35f4ac](https://github.com/angular/angular/commit/926c35f4ac70f5e4d142e545d6d056dd67aac97b) | docs | Deprecate class and InjectionToken and resolvers ([#47924](https://github.com/angular/angular/pull/47924)) |
|
||||
### common
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
@@ -19,27 +152,75 @@ AleksanderBodurri, Alvaro Junqueira, Dylan Hunn, Joey Perrott, Matthieu Riegler,
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [0cf11167f1](https://github.com/angular/angular/commit/0cf11167f13108992ec781e88ab2a7d1fc7f5a0d) | fix | incorrectly detecting forward refs when symbol already exists in file ([#48988](https://github.com/angular/angular/pull/48988)) |
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [a154db8a81](https://github.com/angular/angular/commit/a154db8a81cbdfed8c3d0db1e2a5bf43aa3e0bbf) | feat | add ng generate schematic to convert declarations to standalone ([#48790](https://github.com/angular/angular/pull/48790)) |
|
||||
| [345e737daa](https://github.com/angular/angular/commit/345e737daa7b9f635a4c2923358e5e765f716434) | feat | add ng generate schematic to convert to standalone bootstrapping APIs ([#48848](https://github.com/angular/angular/pull/48848)) |
|
||||
| [e7318fc758](https://github.com/angular/angular/commit/e7318fc758d9e64d1a7f60a2c7071a769b73e7d8) | feat | add ng generate schematic to remove unnecessary modules ([#48832](https://github.com/angular/angular/pull/48832)) |
|
||||
### language-service
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [4ae384fd61](https://github.com/angular/angular/commit/4ae384fd619a13eaadf737d08a97f07e1f6b273c) | feat | Allow auto-imports of a pipe via quick fix when its selector is used, both directly and via reexports. ([#48354](https://github.com/angular/angular/pull/48354)) |
|
||||
| [141333411e](https://github.com/angular/angular/commit/141333411e67769d752c7162e4cb03376022f5e1) | feat | Introduce a new NgModuleIndex, and use it to suggest re-exports. ([#48354](https://github.com/angular/angular/pull/48354)) |
|
||||
| [d0145033bd](https://github.com/angular/angular/commit/d0145033bd11eccd16fa8b61ba9170037d0c62b3) | fix | generate forwardRef for same file imports ([#48898](https://github.com/angular/angular/pull/48898)) |
|
||||
### migrations
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [2796230e95](https://github.com/angular/angular/commit/2796230e953eb8c29d6227a1a3858f5f08a8f200) | fix | add `enum` in `mode` option in `standalone` schema ([#48851](https://github.com/angular/angular/pull/48851)) |
|
||||
| [816e76a578](https://github.com/angular/angular/commit/816e76a5789b041fee78ddd278c0e0d19b9a617a) | fix | automatically prune root module after bootstrap step ([#49030](https://github.com/angular/angular/pull/49030)) |
|
||||
| [bdbf21d04b](https://github.com/angular/angular/commit/bdbf21d04ba74a6f73469242076d6ce697c57edf) | fix | avoid generating imports with forward slashes ([#48993](https://github.com/angular/angular/pull/48993)) |
|
||||
| [32cf4e5cb9](https://github.com/angular/angular/commit/32cf4e5cb989f365296d519dddf72fb38ca47c40) | fix | avoid internal modules when generating imports ([#48958](https://github.com/angular/angular/pull/48958)) |
|
||||
| [521ccfbe6c](https://github.com/angular/angular/commit/521ccfbe6ce9af1a7ddd6ab5e70151b7198f82ef) | fix | avoid interrupting the migration if language service lookup fails ([#49010](https://github.com/angular/angular/pull/49010)) |
|
||||
| [a40cd47aa7](https://github.com/angular/angular/commit/a40cd47aa7ebccfbeeb26e397e03f1372aa10a55) | fix | avoid modifying testing modules without declarations ([#48921](https://github.com/angular/angular/pull/48921)) |
|
||||
| [1afa6ed322](https://github.com/angular/angular/commit/1afa6ed3227e784e3fe2b4b31443961589cb6332) | fix | don't add ModuleWithProviders to standalone test components ([#48987](https://github.com/angular/angular/pull/48987)) |
|
||||
| [c98c6a8452](https://github.com/angular/angular/commit/c98c6a845286b9b89daf275a9c4a2bdbc7ad77a7) | fix | don't copy animations modules into the imports of test components ([#49147](https://github.com/angular/angular/pull/49147)) |
|
||||
| [8389557848](https://github.com/angular/angular/commit/83895578488bd35c7e47609f092907eb0f53f435) | fix | don't copy unmigrated declarations into imports array ([#48882](https://github.com/angular/angular/pull/48882)) |
|
||||
| [f82bdc4b01](https://github.com/angular/angular/commit/f82bdc4b01f93a7103870449d37da61cc4c4f179) | fix | don't delete classes that may provide dependencies transitively ([#48866](https://github.com/angular/angular/pull/48866)) |
|
||||
| [759db12e0b](https://github.com/angular/angular/commit/759db12e0b618fcb51f4cb141adeb49bfa495a60) | fix | duplicated comments on migrated classes ([#48966](https://github.com/angular/angular/pull/48966)) |
|
||||
| [ba38178d19](https://github.com/angular/angular/commit/ba38178d1918d413f9c2260c40eb6542eadfddba) | fix | generate forwardRef for same file imports ([#48898](https://github.com/angular/angular/pull/48898)) |
|
||||
| [03fcb36cfd](https://github.com/angular/angular/commit/03fcb36cfd36731028bf288f156e16cb8ac4c758) | fix | migrate HttpClientModule to provideHttpClient() ([#48949](https://github.com/angular/angular/pull/48949)) |
|
||||
| [2de6dae16d](https://github.com/angular/angular/commit/2de6dae16d4b0b83f0517a3033cda44ba44154ed) | fix | migrate RouterModule.forRoot with a config object to use features ([#48935](https://github.com/angular/angular/pull/48935)) |
|
||||
| [770191cf1f](https://github.com/angular/angular/commit/770191cf1f1254546625dfa7a882b716c3f0aab3) | fix | migrate tests when switching to standalone bootstrap API ([#48987](https://github.com/angular/angular/pull/48987)) |
|
||||
| [c7926b5773](https://github.com/angular/angular/commit/c7926b57730c23f765a00d3dd9f92079c95e87e0) | fix | move standalone migrations into imports ([#48987](https://github.com/angular/angular/pull/48987)) |
|
||||
| [65c74ed93e](https://github.com/angular/angular/commit/65c74ed93e04cb560c27838d440c6aa7a9859a4e) | fix | normalize paths to posix ([#48850](https://github.com/angular/angular/pull/48850)) |
|
||||
| [6377487b1a](https://github.com/angular/angular/commit/6377487b1ab7679cef9a44f88440fe5e8eb97480) | fix | only exclude bootstrapped declarations from initial standalone migration ([#48987](https://github.com/angular/angular/pull/48987)) |
|
||||
| [e9e4449a43](https://github.com/angular/angular/commit/e9e4449a43430e026e61b0f05ebd32dd830fa916) | fix | preserve tsconfig in standalone migration ([#48987](https://github.com/angular/angular/pull/48987)) |
|
||||
| [ffad1b49d9](https://github.com/angular/angular/commit/ffad1b49d95ab90637e7184f92cb5136d490d865) | fix | reduce number of files that need to be checked ([#48987](https://github.com/angular/angular/pull/48987)) |
|
||||
| [ba7a757cc5](https://github.com/angular/angular/commit/ba7a757cc5a2f3f942adcbabdcd5b7aef33ea493) | fix | return correct alias when conflicting import exists ([#49139](https://github.com/angular/angular/pull/49139)) |
|
||||
| [49a7c9f94a](https://github.com/angular/angular/commit/49a7c9f94ae8f89907da8b3620242e62f87ec5a4) | fix | standalone migration incorrectly throwing path error for multi app projects ([#48958](https://github.com/angular/angular/pull/48958)) |
|
||||
| [584976e6c8](https://github.com/angular/angular/commit/584976e6c8a783d40578ab191132673300394a52) | fix | support --defaults in standalone migration ([#48921](https://github.com/angular/angular/pull/48921)) |
|
||||
| [03f47ac901](https://github.com/angular/angular/commit/03f47ac9019eddbcb373b50c41bc6f523293ece1) | fix | use consistent quotes in generated imports ([#48876](https://github.com/angular/angular/pull/48876)) |
|
||||
| [ebae506d89](https://github.com/angular/angular/commit/ebae506d894a90c38e0f2dd1e948acabdb0fdf2e) | fix | use import remapper in root component ([#49046](https://github.com/angular/angular/pull/49046)) |
|
||||
| [40c976c909](https://github.com/angular/angular/commit/40c976c90975878852a87b7722076eb78944098b) | fix | use NgForOf instead of NgFor ([#49022](https://github.com/angular/angular/pull/49022)) |
|
||||
| [4ac25b2aff](https://github.com/angular/angular/commit/4ac25b2affab4f959ad8c111f1e429a05b435422) | perf | avoid re-traversing nodes when resolving bootstrap call dependencies ([#49010](https://github.com/angular/angular/pull/49010)) |
|
||||
| [26cb7ab2e6](https://github.com/angular/angular/commit/26cb7ab2e6ac9b61904361a8a544467b69eef3f3) | perf | speed up language service lookups ([#49010](https://github.com/angular/angular/pull/49010)) |
|
||||
### platform-browser
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [bf4ad38117](https://github.com/angular/angular/commit/bf4ad3811762d9ba43d18c3360d014a9ceb06b4d) | fix | remove styles from DOM of destroyed components ([#48298](https://github.com/angular/angular/pull/48298)) |
|
||||
### platform-server
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [25e220a23a](https://github.com/angular/angular/commit/25e220a23ab90520efc65f05cd9b7a22db582b87) | fix | avoid duplicate TransferState info after renderApplication call ([#49094](https://github.com/angular/angular/pull/49094)) |
|
||||
### router
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [31b94c762f](https://github.com/angular/angular/commit/31b94c762fc91ab6cabe08ea6812780fdcf92a64) | feat | Add a withNavigationErrorHandler feature to provideRouter ([#48551](https://github.com/angular/angular/pull/48551)) |
|
||||
| [dedac8d3f7](https://github.com/angular/angular/commit/dedac8d3f73ebf4f05b773454e2a22ab5fa4bf7c) | feat | Add test helper for trigger navigations in tests ([#48552](https://github.com/angular/angular/pull/48552)) |
|
||||
## Special Thanks
|
||||
Alex Castle, Andrew Scott, Dylan Hunn, Jessica Janiuk, Kian Yang Lee, Kristiyan Kostadinov, Matthieu Riegler, Pawel Kozlowski, Redouane Bekkouche, Simona Cotin and Walid Bouguima
|
||||
Alan Agius, Alex Castle, Alex Rickabaugh, Andrew Kushnir, Andrew Scott, Dylan Hunn, Ikko Eltociear Ashimine, Ilyass, Jessica Janiuk, Joey Perrott, John Manners, Kalbarczyk, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Pawel Kozlowski, Virginia Dooley, Walid Bouguima, cexbrayat and mgechev
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.1.5"></a>
|
||||
# 15.1.5 (2023-02-15)
|
||||
### forms
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [5f2a3edcf2](https://github.com/angular/angular/commit/5f2a3edcf27cfe6ffc6ae4d67ca2b47953f26336) | fix | Make radio buttons respect `[attr.disabled]` ([#48864](https://github.com/angular/angular/pull/48864)) |
|
||||
## Special Thanks
|
||||
AleksanderBodurri, Alvaro Junqueira, Dylan Hunn, Joey Perrott, Matthieu Riegler, PaloMiklo and Paul Gschwendtner
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
@@ -82,73 +263,6 @@ Alan Agius, Besim Gürbüz, Brecht Billiet, Dario Piotrowicz, Dylan Hunn, Iván
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.0-next.3"></a>
|
||||
# 15.2.0-next.3 (2023-02-02)
|
||||
### animations
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [b4187548ca](https://github.com/angular/angular/commit/b4187548cae42f25624bf7ab7ad0cca121242de7) | fix | fix non-animatable warnings for easing ([#48583](https://github.com/angular/angular/pull/48583)) |
|
||||
### common
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [a055196c55](https://github.com/angular/angular/commit/a055196c55c57de281ff7167cd4dfb3df783c337) | fix | warn if using ngSrcset without a configured image loader ([#48804](https://github.com/angular/angular/pull/48804)) |
|
||||
### compiler
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [06e161f2dd](https://github.com/angular/angular/commit/06e161f2dd78b42ad1938578f4d730a41404a24f) | fix | incorrect code when non-null assertion is used after a safe access ([#48801](https://github.com/angular/angular/pull/48801)) |
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [345e737daa](https://github.com/angular/angular/commit/345e737daa7b9f635a4c2923358e5e765f716434) | feat | add ng generate schematic to convert to standalone bootstrapping APIs ([#48848](https://github.com/angular/angular/pull/48848)) |
|
||||
### migrations
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [2796230e95](https://github.com/angular/angular/commit/2796230e953eb8c29d6227a1a3858f5f08a8f200) | fix | add `enum` in `mode` option in `standalone` schema ([#48851](https://github.com/angular/angular/pull/48851)) |
|
||||
| [a40cd47aa7](https://github.com/angular/angular/commit/a40cd47aa7ebccfbeeb26e397e03f1372aa10a55) | fix | avoid modifying testing modules without declarations ([#48921](https://github.com/angular/angular/pull/48921)) |
|
||||
| [8389557848](https://github.com/angular/angular/commit/83895578488bd35c7e47609f092907eb0f53f435) | fix | don't copy unmigrated declarations into imports array ([#48882](https://github.com/angular/angular/pull/48882)) |
|
||||
| [f82bdc4b01](https://github.com/angular/angular/commit/f82bdc4b01f93a7103870449d37da61cc4c4f179) | fix | don't delete classes that may provide dependencies transitively ([#48866](https://github.com/angular/angular/pull/48866)) |
|
||||
| [04e0ac3d7c](https://github.com/angular/angular/commit/04e0ac3d7ca89bf38d4d2a38b7ca120d9b7b96ae) | fix | migration host incorrectly reading empty files ([#48849](https://github.com/angular/angular/pull/48849)) |
|
||||
| [65c74ed93e](https://github.com/angular/angular/commit/65c74ed93e04cb560c27838d440c6aa7a9859a4e) | fix | normalize paths to posix ([#48850](https://github.com/angular/angular/pull/48850)) |
|
||||
| [584976e6c8](https://github.com/angular/angular/commit/584976e6c8a783d40578ab191132673300394a52) | fix | support --defaults in standalone migration ([#48921](https://github.com/angular/angular/pull/48921)) |
|
||||
| [03f47ac901](https://github.com/angular/angular/commit/03f47ac9019eddbcb373b50c41bc6f523293ece1) | fix | use consistent quotes in generated imports ([#48876](https://github.com/angular/angular/pull/48876)) |
|
||||
### platform-server
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [2fc5b70fce](https://github.com/angular/angular/commit/2fc5b70fcedb8ac35b825b245c0ae394dc125244) | fix | insert transfer state `script` before other `script` tags ([#48868](https://github.com/angular/angular/pull/48868)) |
|
||||
### router
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [dedac8d3f7](https://github.com/angular/angular/commit/dedac8d3f73ebf4f05b773454e2a22ab5fa4bf7c) | feat | Add test helper for trigger navigations in tests ([#48552](https://github.com/angular/angular/pull/48552)) |
|
||||
| [16ef770db8](https://github.com/angular/angular/commit/16ef770db803ce4037a90c72477da412642dfb33) | fix | Handle routerLink directive on svg anchors. ([#48857](https://github.com/angular/angular/pull/48857)) |
|
||||
## Special Thanks
|
||||
Alan Agius, Andrew Scott, Besim Gürbüz, Brecht Billiet, Dario Piotrowicz, Dylan Hunn, Iván Navarro, Kristiyan Kostadinov, Matthieu Riegler, Onkar Ruikar, Payam Valadkhan, Santosh Yadav, Virginia Dooley and Walid Bouguima
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.0-next.2"></a>
|
||||
# 15.2.0-next.2 (2023-01-25)
|
||||
### compiler
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [bc8cfa2552](https://github.com/angular/angular/commit/bc8cfa25520c3b8b0a506c69a269e42a63f097d6) | fix | handle css selectors with space after an escaped character. ([#48558](https://github.com/angular/angular/pull/48558)) |
|
||||
### compiler-cli
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [4da1f2948c](https://github.com/angular/angular/commit/4da1f2948cc67b68527a91579ee14bb1a22b0c58) | fix | resolve deprecation warning ([#48812](https://github.com/angular/angular/pull/48812)) |
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [a154db8a81](https://github.com/angular/angular/commit/a154db8a81cbdfed8c3d0db1e2a5bf43aa3e0bbf) | feat | add ng generate schematic to convert declarations to standalone ([#48790](https://github.com/angular/angular/pull/48790)) |
|
||||
| [e7318fc758](https://github.com/angular/angular/commit/e7318fc758d9e64d1a7f60a2c7071a769b73e7d8) | feat | add ng generate schematic to remove unnecessary modules ([#48832](https://github.com/angular/angular/pull/48832)) |
|
||||
### router
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [4dcab333ae](https://github.com/angular/angular/commit/4dcab333ae009f923cf3864e20ee47e43d32dfe6) | fix | 'createUrlTreeFromSnapshot' with empty paths and named outlets ([#48734](https://github.com/angular/angular/pull/48734)) |
|
||||
## Special Thanks
|
||||
Alan Agius, AleksanderBodurri, Andrew Kushnir, Andrew Scott, Charles Lyding, Dylan Hunn, Jessica Janiuk, JoostK, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Payam Valadkhan, Virginia Dooley, Yann Thomas LE MOIGNE and dario-piotrowicz
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.1.2"></a>
|
||||
# 15.1.2 (2023-01-25)
|
||||
### compiler
|
||||
@@ -168,36 +282,6 @@ Alan Agius, AleksanderBodurri, Andrew Kushnir, Andrew Scott, Charles Lyding, Dyl
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.0-next.1"></a>
|
||||
# 15.2.0-next.1 (2023-01-18)
|
||||
## Deprecations
|
||||
###
|
||||
- Class and `InjectionToken` guards and resolvers are
|
||||
deprecated. Instead, write guards as plain JavaScript functions and
|
||||
inject dependencies with `inject` from `@angular/core`.
|
||||
###
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [926c35f4ac](https://github.com/angular/angular/commit/926c35f4ac70f5e4d142e545d6d056dd67aac97b) | docs | Deprecate class and InjectionToken and resolvers ([#47924](https://github.com/angular/angular/pull/47924)) |
|
||||
### common
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [8802b4aab9](https://github.com/angular/angular/commit/8802b4aab9600870f3e09f198c993845587e9622) | fix | Update `Location` to get a normalized URL valid in case a represented URL starts with the substring equals `APP_BASE_HREF` ([#48489](https://github.com/angular/angular/pull/48489)) |
|
||||
| [5f21c6d627](https://github.com/angular/angular/commit/5f21c6d627892dfad942b55f13861c213f9c0afb) | perf | avoid excessive DOM mutation in NgClass ([#48433](https://github.com/angular/angular/pull/48433)) |
|
||||
### core
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [f00bf71411](https://github.com/angular/angular/commit/f00bf714110100549111bd27345943ab8830128c) | fix | makeEnvironmentProviders should accept EnvironmentProviders ([#48720](https://github.com/angular/angular/pull/48720)) |
|
||||
### language-service
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [4ae384fd61](https://github.com/angular/angular/commit/4ae384fd619a13eaadf737d08a97f07e1f6b273c) | feat | Allow auto-imports of a pipe via quick fix when its selector is used, both directly and via reexports. ([#48354](https://github.com/angular/angular/pull/48354)) |
|
||||
| [141333411e](https://github.com/angular/angular/commit/141333411e67769d752c7162e4cb03376022f5e1) | feat | Introduce a new NgModuleIndex, and use it to suggest re-exports. ([#48354](https://github.com/angular/angular/pull/48354)) |
|
||||
## Special Thanks
|
||||
Alex Rickabaugh, Andrew Kushnir, Andrew Scott, Aristeidis Bampakos, Bob Watson, Dylan Hunn, Jens, Konstantin Kharitonov, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Pawel Kozlowski, Vladyslav Slipchenko, ced, dario-piotrowicz, mgechev and ノウラ
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.1.1"></a>
|
||||
# 15.1.1 (2023-01-18)
|
||||
### common
|
||||
@@ -214,17 +298,6 @@ Alan Agius, Alex Rickabaugh, Andrew Scott, Aristeidis Bampakos, Bob Watson, Jens
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.2.0-next.0"></a>
|
||||
# 15.2.0-next.0 (2023-01-11)
|
||||
### router
|
||||
| Commit | Type | Description |
|
||||
| -- | -- | -- |
|
||||
| [31b94c762f](https://github.com/angular/angular/commit/31b94c762fc91ab6cabe08ea6812780fdcf92a64) | feat | Add a withNavigationErrorHandler feature to provideRouter ([#48551](https://github.com/angular/angular/pull/48551)) |
|
||||
## Special Thanks
|
||||
Alan Agius, Alex Rickabaugh, Andrew Scott, Paul Gschwendtner and angular-robot[bot]
|
||||
|
||||
<!-- CHANGELOG SPLIT MARKER -->
|
||||
|
||||
<a name="15.1.0"></a>
|
||||
# 15.1.0 (2023-01-10)
|
||||
## Deprecations
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<h1 align="center">Angular - The modern web developer's platform.</h1>
|
||||
<h1 align="center">Angular - The modern web developer's platform</h1>
|
||||
|
||||
<p align="center">
|
||||
<img src="aio/src/assets/images/logos/angular/angular.png" alt="angular-logo" width="120px" height="120px"/>
|
||||
<br>
|
||||
<i>Angular is a development platform for building mobile and desktop web applications
|
||||
<br> using Typescript/JavaScript and other languages.</i>
|
||||
<br> using TypeScript/JavaScript and other languages.</i>
|
||||
<br>
|
||||
</p>
|
||||
|
||||
|
||||
@@ -26,12 +26,10 @@ http_archive(
|
||||
http_archive(
|
||||
name = "build_bazel_rules_nodejs",
|
||||
patches = [
|
||||
# TODO(devversion): remove when https://github.com/bazelbuild/rules_nodejs/pull/3605 is available.
|
||||
"//tools:bazel-repo-patches/rules_nodejs__#3605.patch",
|
||||
"//tools/esm-interop:patches/bazel/nodejs_binary_esm_support.patch",
|
||||
],
|
||||
sha256 = "c29944ba9b0b430aadcaf3bf2570fece6fc5ebfb76df145c6cdad40d65c20811",
|
||||
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.7.0/rules_nodejs-5.7.0.tar.gz"],
|
||||
sha256 = "94070eff79305be05b7699207fbac5d2608054dd53e6109f7d00d923919ff45a",
|
||||
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.8.2/rules_nodejs-5.8.2.tar.gz"],
|
||||
)
|
||||
|
||||
load("@build_bazel_rules_nodejs//:repositories.bzl", "build_bazel_rules_nodejs_dependencies")
|
||||
@@ -62,7 +60,7 @@ load("@rules_nodejs//nodejs:repositories.bzl", "nodejs_register_toolchains")
|
||||
|
||||
nodejs_register_toolchains(
|
||||
name = "nodejs",
|
||||
node_version = "16.13.0",
|
||||
node_version = "16.14.0",
|
||||
)
|
||||
|
||||
# Download npm dependencies.
|
||||
@@ -192,10 +190,10 @@ cldr_xml_data_repository(
|
||||
# sass rules
|
||||
http_archive(
|
||||
name = "io_bazel_rules_sass",
|
||||
sha256 = "38442f09a6f6f4e932e86ed29b86d5026b41d9ebbe9d017fe8a5684e1826b821",
|
||||
strip_prefix = "rules_sass-b603e6f0daf73d5aa9dca768b45dde30e5b288bc",
|
||||
sha256 = "de516110be32fcce328cb93ec4bf06f7a6e978e60bfd9d628fb5571c4a0afade",
|
||||
strip_prefix = "rules_sass-898e4dd048584152bfbd77abd9ed0c3fe28c86ac",
|
||||
urls = [
|
||||
"https://github.com/bazelbuild/rules_sass/archive/b603e6f0daf73d5aa9dca768b45dde30e5b288bc.zip",
|
||||
"https://github.com/bazelbuild/rules_sass/archive/898e4dd048584152bfbd77abd9ed0c3fe28c86ac.zip",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "15.1.0-next.2",
|
||||
"@angular/common": "15.1.0-next.2",
|
||||
"@angular/compiler": "15.1.0-next.2",
|
||||
"@angular/core": "15.1.0-next.2",
|
||||
"@angular/platform-browser": "15.1.0-next.2",
|
||||
"@angular/platform-browser-dynamic": "15.1.0-next.2",
|
||||
"@angular/animations": "~15.2.0",
|
||||
"@angular/common": "~15.2.0",
|
||||
"@angular/compiler": "~15.2.0",
|
||||
"@angular/core": "~15.2.0",
|
||||
"@angular/platform-browser": "~15.2.0",
|
||||
"@angular/platform-browser-dynamic": "~15.2.0",
|
||||
"rxjs": "^7.5.2",
|
||||
"tslib": "^2.3.1",
|
||||
"zone.js": "^0.12.0"
|
||||
@@ -22,9 +22,9 @@
|
||||
"e2e": "ng e2e"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular-devkit/build-angular": "~15.0.1",
|
||||
"@angular/cli": "~15.0.1",
|
||||
"@angular/compiler-cli": "~15.0.1",
|
||||
"@angular-devkit/build-angular": "~15.2.0",
|
||||
"@angular/cli": "~15.2.0",
|
||||
"@angular/compiler-cli": "~15.2.0",
|
||||
"@types/jasmine": "~4.3.0",
|
||||
"@types/node": "^12.11.1",
|
||||
"codelyzer": "^6.0.0",
|
||||
@@ -38,6 +38,6 @@
|
||||
"protractor": "~7.0.0",
|
||||
"ts-node": "~10.9.0",
|
||||
"tslint": "~6.1.0",
|
||||
"typescript": "~4.8.4"
|
||||
"typescript": "~4.9.3"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1525
-1304
File diff suppressed because it is too large
Load Diff
@@ -6,24 +6,22 @@ import { Component, OnDestroy } from '@angular/core';
|
||||
template: '<p>{{message}}</p>'
|
||||
})
|
||||
export class CountdownTimerComponent implements OnDestroy {
|
||||
|
||||
intervalId = 0;
|
||||
message = '';
|
||||
seconds = 11;
|
||||
|
||||
ngOnDestroy() { this.clearTimer(); }
|
||||
ngOnDestroy() { this.clearTimer?.(); }
|
||||
|
||||
start() { this.countDown(); }
|
||||
stop() {
|
||||
this.clearTimer();
|
||||
this.clearTimer?.();
|
||||
this.message = `Holding at T-${this.seconds} seconds`;
|
||||
}
|
||||
|
||||
private clearTimer() { clearInterval(this.intervalId); }
|
||||
private clearTimer: VoidFunction | undefined;
|
||||
|
||||
private countDown() {
|
||||
this.clearTimer();
|
||||
this.intervalId = window.setInterval(() => {
|
||||
this.clearTimer?.();
|
||||
const interval = setInterval(() => {
|
||||
this.seconds -= 1;
|
||||
if (this.seconds === 0) {
|
||||
this.message = 'Blast off!';
|
||||
@@ -32,5 +30,6 @@ export class CountdownTimerComponent implements OnDestroy {
|
||||
this.message = `T-${this.seconds} seconds and counting`;
|
||||
}
|
||||
}, 1000);
|
||||
this.clearTimer = () => clearInterval(interval);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ export class AdBannerComponent implements OnInit, OnDestroy {
|
||||
currentAdIndex = -1;
|
||||
|
||||
@ViewChild(AdDirective, {static: true}) adHost!: AdDirective;
|
||||
interval: number|undefined;
|
||||
|
||||
private clearTimer: VoidFunction | undefined;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadComponent();
|
||||
@@ -31,7 +32,7 @@ export class AdBannerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
clearInterval(this.interval);
|
||||
this.clearTimer?.();
|
||||
}
|
||||
|
||||
loadComponent() {
|
||||
@@ -46,9 +47,10 @@ export class AdBannerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
getAds() {
|
||||
this.interval = setInterval(() => {
|
||||
const interval = setInterval(() => {
|
||||
this.loadComponent();
|
||||
}, 3000);
|
||||
this.clearTimer = () => clearInterval(interval);
|
||||
}
|
||||
}
|
||||
// #enddocregion class
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
|
||||
import { ApplicationRef, ComponentFactoryResolver, Injectable, Injector } from '@angular/core';
|
||||
import { ApplicationRef, createComponent, EnvironmentInjector, Injectable } from '@angular/core';
|
||||
import { NgElement, WithProperties } from '@angular/elements';
|
||||
import { PopupComponent } from './popup.component';
|
||||
|
||||
|
||||
@Injectable()
|
||||
export class PopupService {
|
||||
constructor(private injector: Injector,
|
||||
private applicationRef: ApplicationRef,
|
||||
private componentFactoryResolver: ComponentFactoryResolver) {}
|
||||
constructor(private injector: EnvironmentInjector,
|
||||
private applicationRef: ApplicationRef) {}
|
||||
|
||||
// Previous dynamic-loading method required you to set up infrastructure
|
||||
// before adding the popup to the DOM.
|
||||
@@ -17,8 +16,7 @@ export class PopupService {
|
||||
const popup = document.createElement('popup-component');
|
||||
|
||||
// Create the component and wire it up with the element
|
||||
const factory = this.componentFactoryResolver.resolveComponentFactory(PopupComponent);
|
||||
const popupComponentRef = factory.create(this.injector, [], popup);
|
||||
const popupComponentRef = createComponent(PopupComponent, {environmentInjector: this.injector, hostElement: popup});
|
||||
|
||||
// Attach to the view so that the change detector knows to run
|
||||
this.applicationRef.attachView(popupComponentRef.hostView);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"tests": [
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"projectType": "testing",
|
||||
"tests": [
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@ export function docRegionDelaySequence(console: Console) {
|
||||
// #docregion delay_sequence
|
||||
function sequenceSubscriber(observer: Observer<number>) {
|
||||
const seq = [1, 2, 3];
|
||||
let timeoutId: any;
|
||||
let clearTimer: VoidFunction | undefined;
|
||||
|
||||
// Will run through an array of numbers, emitting one value
|
||||
// per second until it gets to the end of the array.
|
||||
function doInSequence(arr: number[], idx: number) {
|
||||
timeoutId = setTimeout(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
observer.next(arr[idx]);
|
||||
if (idx === arr.length - 1) {
|
||||
observer.complete();
|
||||
@@ -19,6 +19,7 @@ export function docRegionDelaySequence(console: Console) {
|
||||
doInSequence(arr, ++idx);
|
||||
}
|
||||
}, 1000);
|
||||
clearTimer = () => clearTimeout(timeout);
|
||||
}
|
||||
|
||||
doInSequence(seq, 0);
|
||||
@@ -26,7 +27,7 @@ export function docRegionDelaySequence(console: Console) {
|
||||
// Unsubscribe should clear the timeout to stop execution
|
||||
return {
|
||||
unsubscribe() {
|
||||
clearTimeout(timeoutId);
|
||||
clearTimer?.();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -85,9 +86,9 @@ export function docRegionMulticastSequence(console: Console, runSequence: boolea
|
||||
const seq = [1, 2, 3];
|
||||
// Keep track of each observer (one for every active subscription)
|
||||
const observers: Observer<unknown>[] = [];
|
||||
// Still a single timeoutId because there will only ever be one
|
||||
// Still a single timer because there will only ever be one
|
||||
// set of values being generated, multicasted to each subscriber
|
||||
let timeoutId: any;
|
||||
let clearTimer: VoidFunction | undefined;
|
||||
|
||||
// Return the subscriber function (runs when subscribe()
|
||||
// function is invoked)
|
||||
@@ -115,7 +116,7 @@ export function docRegionMulticastSequence(console: Console, runSequence: boolea
|
||||
observers.splice(observers.indexOf(observer), 1);
|
||||
// If there's no more listeners, do cleanup
|
||||
if (observers.length === 0) {
|
||||
clearTimeout(timeoutId);
|
||||
clearTimer?.();
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -123,7 +124,7 @@ export function docRegionMulticastSequence(console: Console, runSequence: boolea
|
||||
// Run through an array of numbers, emitting one value
|
||||
// per second until it gets to the end of the array.
|
||||
function doSequence(sequenceObserver: Observer<number>, arr: number[], idx: number) {
|
||||
timeoutId = setTimeout(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
console.log('Emitting ' + arr[idx]);
|
||||
sequenceObserver.next(arr[idx]);
|
||||
if (idx === arr.length - 1) {
|
||||
@@ -132,6 +133,7 @@ export function docRegionMulticastSequence(console: Console, runSequence: boolea
|
||||
doSequence(sequenceObserver, arr, ++idx);
|
||||
}
|
||||
}, 1000);
|
||||
clearTimer = () => clearTimeout(timeout);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,20 +1,15 @@
|
||||
// #docplaster
|
||||
// #docregion
|
||||
import { of, pipe, range, throwError, timer, zip } from 'rxjs';
|
||||
import { timer } from 'rxjs';
|
||||
import { ajax } from 'rxjs/ajax';
|
||||
import { map, mergeMap, retryWhen } from 'rxjs/operators';
|
||||
import { retry } from 'rxjs/operators';
|
||||
|
||||
export function backoff(maxTries: number, delay: number) {
|
||||
return pipe(
|
||||
retryWhen(attempts =>
|
||||
zip(range(1, maxTries + 1), attempts).pipe(
|
||||
mergeMap(([i, err]) => (i > maxTries) ? throwError(err) : of(i)),
|
||||
map(i => i * i),
|
||||
mergeMap(v => timer(v * delay)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
export function backoff(maxTries: number, initialDelay: number) {
|
||||
return retry({
|
||||
count: maxTries,
|
||||
delay: (error, retryCount) => timer(initialDelay * retryCount ** 2),
|
||||
});
|
||||
}
|
||||
|
||||
// #enddocregion
|
||||
/*
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
import { of } from 'rxjs';
|
||||
import { docRegionTypeahead } from './typeahead';
|
||||
|
||||
@@ -71,7 +69,7 @@ describe('typeahead', () => {
|
||||
|
||||
// Helpers
|
||||
interface MockTask {
|
||||
id: NodeJS.Timeout;
|
||||
id: ReturnType<typeof setTimeout>;
|
||||
fn: () => unknown;
|
||||
delay: number;
|
||||
recurring: boolean;
|
||||
@@ -86,12 +84,12 @@ describe('typeahead', () => {
|
||||
static install(mockTime = 0): MockClock['tick'] {
|
||||
const mocked = new this(mockTime);
|
||||
|
||||
spyOn(global, 'clearInterval').and.callFake(id => mocked.clearTask(id as MockTask['id']));
|
||||
spyOn(global, 'clearTimeout').and.callFake(id => mocked.clearTask(id as MockTask['id']));
|
||||
spyOn(global, 'setInterval').and.callFake(
|
||||
spyOn(globalThis, 'clearInterval').and.callFake(id => mocked.clearTask(id as MockTask['id']));
|
||||
spyOn(globalThis, 'clearTimeout').and.callFake(id => mocked.clearTask(id as MockTask['id']));
|
||||
spyOn(globalThis, 'setInterval').and.callFake(
|
||||
((fn: () => unknown, delay: number, ...args: any[]) =>
|
||||
mocked.createTask(fn, delay, true, ...args)) as typeof setInterval);
|
||||
spyOn(global, 'setTimeout').and.callFake(
|
||||
spyOn(globalThis, 'setTimeout').and.callFake(
|
||||
((fn: () => unknown, delay: number, ...args: any[]) =>
|
||||
mocked.createTask(fn, delay, false, ...args)) as typeof setTimeout);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"tests": [
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ export class ToastComponent implements OnInit {
|
||||
// private methods
|
||||
private hide() {
|
||||
this.toastElement.style.opacity = 0;
|
||||
window.setTimeout(() => this.toastElement.style.zIndex = 0, 400);
|
||||
setTimeout(() => this.toastElement.style.zIndex = 0, 400);
|
||||
}
|
||||
|
||||
activate(message = this.defaults.message, title = this.defaults.title) {
|
||||
@@ -34,7 +34,7 @@ export class ToastComponent implements OnInit {
|
||||
this.toastElement.style.opacity = 1;
|
||||
this.toastElement.style.zIndex = 9999;
|
||||
|
||||
window.setTimeout(() => this.hide(), 2500);
|
||||
setTimeout(() => this.hide(), 2500);
|
||||
}
|
||||
}
|
||||
// #enddocregion example
|
||||
|
||||
@@ -32,14 +32,14 @@ export class ToastComponent implements OnInit {
|
||||
// private methods
|
||||
private hide() {
|
||||
this.toastElement.style.opacity = 0;
|
||||
window.setTimeout(() => this.toastElement.style.zIndex = 0, 400);
|
||||
setTimeout(() => this.toastElement.style.zIndex = 0, 400);
|
||||
}
|
||||
|
||||
private show() {
|
||||
console.log(this.message);
|
||||
this.toastElement.style.opacity = 1;
|
||||
this.toastElement.style.zIndex = 9999;
|
||||
window.setTimeout(() => this.hide(), 2500);
|
||||
setTimeout(() => this.hide(), 2500);
|
||||
}
|
||||
}
|
||||
// #enddocregion example
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"projectType": "testing",
|
||||
"tests": [
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
// #docplaster
|
||||
import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import {Component, DebugElement, NO_ERRORS_SCHEMA} from '@angular/core';
|
||||
import {ComponentFixture, fakeAsync, TestBed, tick, waitForAsync} from '@angular/core/testing';
|
||||
import {By} from '@angular/platform-browser';
|
||||
import {provideRouter, Router, RouterLink} from '@angular/router';
|
||||
|
||||
import { RouterLinkDirectiveStub } from '../testing';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
import {AppComponent} from './app.component';
|
||||
|
||||
// #docregion component-stubs
|
||||
@Component({selector: 'app-banner', template: ''})
|
||||
@@ -29,10 +28,10 @@ describe('AppComponent & TestModule', () => {
|
||||
// #docregion testbed-stubs
|
||||
TestBed
|
||||
.configureTestingModule({
|
||||
declarations: [
|
||||
AppComponent, RouterLinkDirectiveStub, BannerStubComponent, RouterOutletStubComponent,
|
||||
WelcomeStubComponent
|
||||
]
|
||||
imports: [RouterLink],
|
||||
providers: [provideRouter([])],
|
||||
declarations:
|
||||
[AppComponent, BannerStubComponent, RouterOutletStubComponent, WelcomeStubComponent]
|
||||
})
|
||||
// #enddocregion testbed-stubs
|
||||
.compileComponents()
|
||||
@@ -55,8 +54,9 @@ describe('AppComponent & NO_ERRORS_SCHEMA', () => {
|
||||
// #enddocregion no-errors-schema
|
||||
BannerStubComponent,
|
||||
// #docregion no-errors-schema
|
||||
RouterLinkDirectiveStub
|
||||
],
|
||||
providers: [provideRouter([])],
|
||||
imports: [RouterLink],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
})
|
||||
// #enddocregion no-errors-schema, mixed-setup
|
||||
@@ -70,21 +70,25 @@ describe('AppComponent & NO_ERRORS_SCHEMA', () => {
|
||||
});
|
||||
|
||||
//////// Testing w/ real root module //////
|
||||
// Tricky because we are disabling the router and its configuration
|
||||
// Better to use RouterTestingModule
|
||||
import { AppModule } from './app.module';
|
||||
import { AppRoutingModule } from './app-routing.module';
|
||||
import {AppModule} from './app.module';
|
||||
import {AppRoutingModule} from './app-routing.module';
|
||||
|
||||
describe('AppComponent & AppModule', () => {
|
||||
beforeEach(waitForAsync(() => {
|
||||
TestBed
|
||||
.configureTestingModule({imports: [AppModule]})
|
||||
.configureTestingModule({
|
||||
imports: [AppModule],
|
||||
})
|
||||
|
||||
// Get rid of app's Router configuration otherwise many failures.
|
||||
// Doing so removes Router declarations; add the Router stubs
|
||||
.overrideModule(AppModule, {
|
||||
remove: {imports: [AppRoutingModule]},
|
||||
add: {declarations: [RouterLinkDirectiveStub, RouterOutletStubComponent]}
|
||||
add: {
|
||||
declarations: [RouterOutletStubComponent],
|
||||
imports: [RouterLink],
|
||||
providers: [provideRouter([])],
|
||||
}
|
||||
})
|
||||
|
||||
.compileComponents()
|
||||
@@ -99,7 +103,7 @@ describe('AppComponent & AppModule', () => {
|
||||
});
|
||||
|
||||
function tests() {
|
||||
let routerLinks: RouterLinkDirectiveStub[];
|
||||
let routerLinks: RouterLink[];
|
||||
let linkDes: DebugElement[];
|
||||
|
||||
// #docregion test-setup
|
||||
@@ -107,11 +111,11 @@ function tests() {
|
||||
fixture.detectChanges(); // trigger initial data binding
|
||||
|
||||
// find DebugElements with an attached RouterLinkStubDirective
|
||||
linkDes = fixture.debugElement.queryAll(By.directive(RouterLinkDirectiveStub));
|
||||
linkDes = fixture.debugElement.queryAll(By.directive(RouterLink));
|
||||
|
||||
// get attached link directive instances
|
||||
// using each DebugElement's injector
|
||||
routerLinks = linkDes.map(de => de.injector.get(RouterLinkDirectiveStub));
|
||||
routerLinks = linkDes.map(de => de.injector.get(RouterLink));
|
||||
});
|
||||
// #enddocregion test-setup
|
||||
|
||||
@@ -121,26 +125,21 @@ function tests() {
|
||||
|
||||
// #docregion tests
|
||||
it('can get RouterLinks from template', () => {
|
||||
expect(routerLinks.length)
|
||||
.withContext('should have 3 routerLinks')
|
||||
.toBe(3);
|
||||
expect(routerLinks[0].linkParams).toBe('/dashboard');
|
||||
expect(routerLinks[1].linkParams).toBe('/heroes');
|
||||
expect(routerLinks[2].linkParams).toBe('/about');
|
||||
expect(routerLinks.length).withContext('should have 3 routerLinks').toBe(3);
|
||||
expect(routerLinks[0].href).toBe('/dashboard');
|
||||
expect(routerLinks[1].href).toBe('/heroes');
|
||||
expect(routerLinks[2].href).toBe('/about');
|
||||
});
|
||||
|
||||
it('can click Heroes link in template', () => {
|
||||
const heroesLinkDe = linkDes[1]; // heroes link DebugElement
|
||||
const heroesLink = routerLinks[1]; // heroes link directive
|
||||
it('can click Heroes link in template', fakeAsync(() => {
|
||||
const heroesLinkDe = linkDes[1]; // heroes link DebugElement
|
||||
|
||||
expect(heroesLink.navigatedTo)
|
||||
.withContext('should not have navigated yet')
|
||||
.toBeNull();
|
||||
TestBed.inject(Router).resetConfig([{path: '**', children: []}]);
|
||||
heroesLinkDe.triggerEventHandler('click', {button: 0});
|
||||
tick();
|
||||
fixture.detectChanges();
|
||||
|
||||
heroesLinkDe.triggerEventHandler('click');
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(heroesLink.navigatedTo).toBe('/heroes');
|
||||
});
|
||||
expect(TestBed.inject(Router).url).toBe('/heroes');
|
||||
}));
|
||||
// #enddocregion tests
|
||||
}
|
||||
|
||||
@@ -1,20 +1,24 @@
|
||||
// #docplaster
|
||||
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {NO_ERRORS_SCHEMA} from '@angular/core';
|
||||
import {TestBed, waitForAsync} from '@angular/core/testing';
|
||||
import {By} from '@angular/platform-browser';
|
||||
import {NavigationEnd, provideRouter, Router} from '@angular/router';
|
||||
import {RouterTestingHarness} from '@angular/router/testing';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
import {filter} from 'rxjs/operators';
|
||||
|
||||
import { addMatchers, asyncData, click } from '../../testing';
|
||||
import { HeroService } from '../model/hero.service';
|
||||
import { getTestHeroes } from '../model/testing/test-heroes';
|
||||
import {addMatchers, click} from '../../testing';
|
||||
import {HeroService} from '../model/hero.service';
|
||||
import {getTestHeroes} from '../model/testing/test-heroes';
|
||||
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
import { DashboardComponent } from './dashboard.component';
|
||||
import { DashboardModule } from './dashboard.module';
|
||||
import {DashboardComponent} from './dashboard.component';
|
||||
import {DashboardModule} from './dashboard.module';
|
||||
|
||||
beforeEach(addMatchers);
|
||||
|
||||
let comp: DashboardComponent;
|
||||
let fixture: ComponentFixture<DashboardComponent>;
|
||||
let harness: RouterTestingHarness;
|
||||
|
||||
//////// Deep ////////////////
|
||||
|
||||
@@ -29,15 +33,15 @@ describe('DashboardComponent (deep)', () => {
|
||||
|
||||
function clickForDeep() {
|
||||
// get first <div class="hero">
|
||||
const heroEl: HTMLElement = fixture.nativeElement.querySelector('.hero');
|
||||
const heroEl: HTMLElement = harness.routeNativeElement!.querySelector('.hero')!;
|
||||
click(heroEl);
|
||||
return firstValueFrom(
|
||||
TestBed.inject(Router).events.pipe(filter(e => e instanceof NavigationEnd)));
|
||||
}
|
||||
});
|
||||
|
||||
//////// Shallow ////////////////
|
||||
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
|
||||
describe('DashboardComponent (shallow)', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule(
|
||||
@@ -50,33 +54,32 @@ describe('DashboardComponent (shallow)', () => {
|
||||
|
||||
function clickForShallow() {
|
||||
// get first <dashboard-hero> DebugElement
|
||||
const heroDe = fixture.debugElement.query(By.css('dashboard-hero'));
|
||||
const heroDe = harness.routeDebugElement!.query(By.css('dashboard-hero'));
|
||||
heroDe.triggerEventHandler('selected', comp.heroes[0]);
|
||||
return Promise.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
/** Add TestBed providers, compile, and create DashboardComponent */
|
||||
function compileAndCreate() {
|
||||
beforeEach(waitForAsync(() => {
|
||||
// #docregion router-spy
|
||||
const routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);
|
||||
const heroServiceSpy = jasmine.createSpyObj('HeroService', ['getHeroes']);
|
||||
|
||||
// #docregion router-harness
|
||||
TestBed
|
||||
.configureTestingModule({
|
||||
providers: [
|
||||
{provide: HeroService, useValue: heroServiceSpy}, {provide: Router, useValue: routerSpy}
|
||||
provideRouter([{path: '**', component: DashboardComponent}]),
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
HeroService,
|
||||
]
|
||||
})
|
||||
// #enddocregion router-spy
|
||||
.compileComponents()
|
||||
.then(() => {
|
||||
fixture = TestBed.createComponent(DashboardComponent);
|
||||
comp = fixture.componentInstance;
|
||||
|
||||
// getHeroes spy returns observable of test heroes
|
||||
heroServiceSpy.getHeroes.and.returnValue(asyncData(getTestHeroes()));
|
||||
.then(async () => {
|
||||
harness = await RouterTestingHarness.create();
|
||||
comp = await harness.navigateByUrl('/', DashboardComponent);
|
||||
TestBed.inject(HttpTestingController).expectOne('api/heroes').flush(getTestHeroes());
|
||||
});
|
||||
// #enddocregion router-harness
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -84,61 +87,38 @@ function compileAndCreate() {
|
||||
* The (almost) same tests for both.
|
||||
* Only change: the way that the first hero is clicked
|
||||
*/
|
||||
function tests(heroClick: () => void) {
|
||||
|
||||
it('should NOT have heroes before ngOnInit', () => {
|
||||
expect(comp.heroes.length)
|
||||
.withContext('should not have heroes before ngOnInit')
|
||||
.toBe(0);
|
||||
});
|
||||
|
||||
it('should NOT have heroes immediately after ngOnInit', () => {
|
||||
fixture.detectChanges(); // runs initial lifecycle hooks
|
||||
|
||||
expect(comp.heroes.length)
|
||||
.withContext('should not have heroes until service promise resolves')
|
||||
.toBe(0);
|
||||
});
|
||||
|
||||
function tests(heroClick: () => Promise<unknown>) {
|
||||
describe('after get dashboard heroes', () => {
|
||||
let router: Router;
|
||||
|
||||
// Trigger component so it gets heroes and binds to them
|
||||
// Trigger component so it gets heroes and binds to them
|
||||
beforeEach(waitForAsync(() => {
|
||||
router = fixture.debugElement.injector.get(Router);
|
||||
fixture.detectChanges(); // runs ngOnInit -> getHeroes
|
||||
fixture.whenStable() // No need for the `lastPromise` hack!
|
||||
.then(() => fixture.detectChanges()); // bind to heroes
|
||||
router = TestBed.inject(Router);
|
||||
harness.detectChanges(); // runs ngOnInit -> getHeroes
|
||||
}));
|
||||
|
||||
it('should HAVE heroes', () => {
|
||||
expect(comp.heroes.length)
|
||||
.withContext('should have heroes after service promise resolves')
|
||||
.toBeGreaterThan(0);
|
||||
.withContext('should have heroes after service promise resolves')
|
||||
.toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should DISPLAY heroes', () => {
|
||||
// Find and examine the displayed heroes
|
||||
// Look for them in the DOM by css class
|
||||
const heroes = fixture.nativeElement.querySelectorAll('dashboard-hero');
|
||||
expect(heroes.length)
|
||||
.withContext('should display 4 heroes')
|
||||
.toBe(4);
|
||||
const heroes = harness.routeNativeElement!.querySelectorAll('dashboard-hero');
|
||||
expect(heroes.length).withContext('should display 4 heroes').toBe(4);
|
||||
});
|
||||
|
||||
// #docregion navigate-test
|
||||
it('should tell ROUTER to navigate when hero clicked', () => {
|
||||
heroClick(); // trigger click on first inner <div class="hero">
|
||||
|
||||
// args passed to router.navigateByUrl() spy
|
||||
const spy = router.navigateByUrl as jasmine.Spy;
|
||||
const navArgs = spy.calls.first().args[0];
|
||||
it('should tell navigate when hero clicked', async () => {
|
||||
await heroClick(); // trigger click on first inner <div class="hero">
|
||||
|
||||
// expecting to navigate to id of the component's first hero
|
||||
const id = comp.heroes[0].id;
|
||||
expect(navArgs)
|
||||
.withContext('should nav to HeroDetail for first hero')
|
||||
.toBe('/heroes/' + id);
|
||||
expect(TestBed.inject(Router).url)
|
||||
.withContext('should nav to HeroDetail for first hero')
|
||||
.toEqual(`/heroes/${id}`);
|
||||
});
|
||||
// #enddocregion navigate-test
|
||||
});
|
||||
|
||||
@@ -1,29 +1,24 @@
|
||||
// #docregion
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import {Component, OnInit} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
|
||||
import { Hero } from '../model/hero';
|
||||
import { HeroService } from '../model/hero.service';
|
||||
import {Hero} from '../model/hero';
|
||||
import {HeroService} from '../model/hero.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-dashboard',
|
||||
templateUrl: './dashboard.component.html',
|
||||
styleUrls: [ './dashboard.component.css' ]
|
||||
styleUrls: ['./dashboard.component.css']
|
||||
})
|
||||
export class DashboardComponent implements OnInit {
|
||||
|
||||
heroes: Hero[] = [];
|
||||
|
||||
// #docregion ctor
|
||||
constructor(
|
||||
private router: Router,
|
||||
private heroService: HeroService) {
|
||||
}
|
||||
constructor(private router: Router, private heroService: HeroService) {}
|
||||
// #enddocregion ctor
|
||||
|
||||
ngOnInit() {
|
||||
this.heroService.getHeroes()
|
||||
.subscribe(heroes => this.heroes = heroes.slice(1, 5));
|
||||
this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes.slice(1, 5));
|
||||
}
|
||||
|
||||
// #docregion goto-detail
|
||||
@@ -35,7 +30,6 @@ export class DashboardComponent implements OnInit {
|
||||
|
||||
get title() {
|
||||
const cnt = this.heroes.length;
|
||||
return cnt === 0 ? 'No Heroes' :
|
||||
cnt === 1 ? 'Top Hero' : `Top ${cnt} Heroes`;
|
||||
return cnt === 0 ? 'No Heroes' : cnt === 1 ? 'Top Hero' : `Top ${cnt} Heroes`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
import { asyncData, ActivatedRouteStub } from '../../testing';
|
||||
|
||||
import { HeroDetailComponent } from './hero-detail.component';
|
||||
import { HeroDetailService } from './hero-detail.service';
|
||||
import { Hero } from '../model/hero';
|
||||
|
||||
////////// Tests ////////////////////
|
||||
|
||||
describe('HeroDetailComponent - no TestBed', () => {
|
||||
let comp: HeroDetailComponent;
|
||||
let expectedHero: Hero;
|
||||
let hds: jasmine.SpyObj<HeroDetailService>;
|
||||
let router: jasmine.SpyObj<Router>;
|
||||
|
||||
beforeEach((done: DoneFn) => {
|
||||
expectedHero = { id: 42, name: 'Bubba' };
|
||||
const activatedRoute = new ActivatedRouteStub({ id: expectedHero.id });
|
||||
router = jasmine.createSpyObj('Router', ['navigate']);
|
||||
|
||||
hds = jasmine.createSpyObj('HeroDetailService', ['getHero', 'saveHero']);
|
||||
hds.getHero.and.returnValue(asyncData(expectedHero));
|
||||
hds.saveHero.and.returnValue(asyncData(expectedHero));
|
||||
|
||||
comp = new HeroDetailComponent(hds, activatedRoute as any, router);
|
||||
comp.ngOnInit();
|
||||
|
||||
// OnInit calls HDS.getHero; wait for it to get the fake hero
|
||||
hds.getHero.calls.first().returnValue.subscribe(() => done());
|
||||
});
|
||||
|
||||
it('should expose the hero retrieved from the service', () => {
|
||||
expect(comp.hero).toBe(expectedHero);
|
||||
});
|
||||
|
||||
it('should navigate when click cancel', () => {
|
||||
comp.cancel();
|
||||
expect(router.navigate.calls.any())
|
||||
.withContext('router.navigate called')
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
it('should save when click save', () => {
|
||||
comp.save();
|
||||
expect(hds.saveHero.calls.any())
|
||||
.withContext('HeroDetailService.save called')
|
||||
.toBe(true);
|
||||
expect(router.navigate.calls.any())
|
||||
.withContext('router.navigate not called yet')
|
||||
.toBe(false);
|
||||
});
|
||||
|
||||
it('should navigate when click save resolves', (done: DoneFn) => {
|
||||
comp.save();
|
||||
// waits for async save to complete before navigating
|
||||
hds.saveHero.calls.first().returnValue
|
||||
.subscribe(() => {
|
||||
expect(router.navigate.calls.any())
|
||||
.withContext('router.navigate called')
|
||||
.toBe(true);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,27 +1,26 @@
|
||||
// #docplaster
|
||||
import { ComponentFixture, fakeAsync, inject, TestBed, tick, waitForAsync } from '@angular/core/testing';
|
||||
import { Router } from '@angular/router';
|
||||
import {provideHttpClient} from '@angular/common/http';
|
||||
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {fakeAsync, TestBed, tick} from '@angular/core/testing';
|
||||
import {provideRouter, Router} from '@angular/router';
|
||||
import {RouterTestingHarness} from '@angular/router/testing';
|
||||
|
||||
import {
|
||||
ActivatedRoute, ActivatedRouteStub, asyncData, click
|
||||
} from '../../testing';
|
||||
import {asyncData, click} from '../../testing';
|
||||
import {Hero} from '../model/hero';
|
||||
import {SharedModule} from '../shared/shared.module';
|
||||
|
||||
import { Hero } from '../model/hero';
|
||||
import { HeroDetailComponent } from './hero-detail.component';
|
||||
import { HeroDetailService } from './hero-detail.service';
|
||||
import { HeroModule } from './hero.module';
|
||||
import {HeroDetailComponent} from './hero-detail.component';
|
||||
import {HeroDetailService} from './hero-detail.service';
|
||||
import {HeroListComponent} from './hero-list.component';
|
||||
import {HeroModule} from './hero.module';
|
||||
|
||||
////// Testing Vars //////
|
||||
let activatedRoute: ActivatedRouteStub;
|
||||
let component: HeroDetailComponent;
|
||||
let fixture: ComponentFixture<HeroDetailComponent>;
|
||||
let harness: RouterTestingHarness;
|
||||
let page: Page;
|
||||
|
||||
////// Tests //////
|
||||
describe('HeroDetailComponent', () => {
|
||||
beforeEach(() => {
|
||||
activatedRoute = new ActivatedRouteStub();
|
||||
});
|
||||
describe('with HeroModule setup', heroModuleSetup);
|
||||
describe('when override its provided HeroDetailService', overrideSetup);
|
||||
describe('with FormsModule setup', formsModuleSetup);
|
||||
@@ -30,10 +29,11 @@ describe('HeroDetailComponent', () => {
|
||||
|
||||
///////////////////
|
||||
|
||||
const testHero = getTestHeroes()[0];
|
||||
function overrideSetup() {
|
||||
// #docregion hds-spy
|
||||
class HeroDetailServiceSpy {
|
||||
testHero: Hero = {id: 42, name: 'Test Hero'};
|
||||
testHero: Hero = {...testHero};
|
||||
|
||||
/* emit cloned test hero */
|
||||
getHero = jasmine.createSpy('getHero').and.callFake(
|
||||
@@ -46,33 +46,22 @@ function overrideSetup() {
|
||||
|
||||
// #enddocregion hds-spy
|
||||
|
||||
// the `id` value is irrelevant because ignored by service stub
|
||||
beforeEach(() => activatedRoute.setParamMap({id: 99999}));
|
||||
|
||||
// #docregion setup-override
|
||||
beforeEach(async () => {
|
||||
const routerSpy = createRouterSpy();
|
||||
|
||||
await TestBed
|
||||
.configureTestingModule({
|
||||
imports: [HeroModule],
|
||||
providers: [
|
||||
{provide: ActivatedRoute, useValue: activatedRoute},
|
||||
{provide: Router, useValue: routerSpy},
|
||||
// #enddocregion setup-override
|
||||
provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]),
|
||||
// HeroDetailService at this level is IRRELEVANT!
|
||||
{provide: HeroDetailService, useValue: {}}
|
||||
// #docregion setup-override
|
||||
]
|
||||
})
|
||||
|
||||
// Override component's own provider
|
||||
// #docregion override-component-method
|
||||
.overrideComponent(
|
||||
HeroDetailComponent,
|
||||
{set: {providers: [{provide: HeroDetailService, useClass: HeroDetailServiceSpy}]}})
|
||||
// #enddocregion override-component-method
|
||||
|
||||
.compileComponents();
|
||||
});
|
||||
// #enddocregion setup-override
|
||||
@@ -81,18 +70,22 @@ function overrideSetup() {
|
||||
let hdsSpy: HeroDetailServiceSpy;
|
||||
|
||||
beforeEach(async () => {
|
||||
await createComponent();
|
||||
harness = await RouterTestingHarness.create();
|
||||
component = await harness.navigateByUrl(`/heroes/${testHero.id}`, HeroDetailComponent);
|
||||
page = new Page();
|
||||
// get the component's injected HeroDetailServiceSpy
|
||||
hdsSpy = fixture.debugElement.injector.get(HeroDetailService) as any;
|
||||
hdsSpy = harness.routeDebugElement!.injector.get(HeroDetailService) as any;
|
||||
|
||||
harness.detectChanges();
|
||||
});
|
||||
|
||||
it('should have called `getHero`', () => {
|
||||
expect(hdsSpy.getHero.calls.count())
|
||||
.withContext('getHero called once')
|
||||
.toBe(1, 'getHero called once');
|
||||
.withContext('getHero called once')
|
||||
.toBe(1, 'getHero called once');
|
||||
});
|
||||
|
||||
it("should display stub hero's name", () => {
|
||||
it('should display stub hero\'s name', () => {
|
||||
expect(page.nameDisplay.textContent).toBe(hdsSpy.testHero.name);
|
||||
});
|
||||
|
||||
@@ -102,62 +95,43 @@ function overrideSetup() {
|
||||
|
||||
page.nameInput.value = newName;
|
||||
|
||||
page.nameInput.dispatchEvent(new Event('input')); // tell Angular
|
||||
page.nameInput.dispatchEvent(new Event('input')); // tell Angular
|
||||
|
||||
expect(component.hero.name)
|
||||
.withContext('component hero has new name')
|
||||
.toBe(newName);
|
||||
expect(component.hero.name).withContext('component hero has new name').toBe(newName);
|
||||
expect(hdsSpy.testHero.name)
|
||||
.withContext('service hero unchanged before save')
|
||||
.toBe(origName);
|
||||
.withContext('service hero unchanged before save')
|
||||
.toBe(origName);
|
||||
|
||||
click(page.saveBtn);
|
||||
expect(hdsSpy.saveHero.calls.count())
|
||||
.withContext('saveHero called once')
|
||||
.toBe(1);
|
||||
expect(hdsSpy.saveHero.calls.count()).withContext('saveHero called once').toBe(1);
|
||||
|
||||
tick(); // wait for async save to complete
|
||||
expect(hdsSpy.testHero.name)
|
||||
.withContext('service hero has new name after save')
|
||||
.toBe(newName);
|
||||
expect(page.navigateSpy.calls.any())
|
||||
.withContext('router.navigate called')
|
||||
.toBe(true);
|
||||
}));
|
||||
// #enddocregion override-tests
|
||||
|
||||
it('fixture injected service is not the component injected service',
|
||||
// inject gets the service from the fixture
|
||||
inject([HeroDetailService], (fixtureService: HeroDetailService) => {
|
||||
// use `fixture.debugElement.injector` to get service from component
|
||||
const componentService = fixture.debugElement.injector.get(HeroDetailService);
|
||||
|
||||
expect(fixtureService)
|
||||
.withContext('service injected from fixture')
|
||||
.not.toBe(componentService);
|
||||
.withContext('service hero has new name after save')
|
||||
.toBe(newName);
|
||||
expect(TestBed.inject(Router).url).toEqual('/heroes');
|
||||
}));
|
||||
}
|
||||
|
||||
////////////////////
|
||||
import { getTestHeroes, TestHeroService, HeroService } from '../model/testing/test-hero.service';
|
||||
import {getTestHeroes} from '../model/testing/test-hero.service';
|
||||
|
||||
const firstHero = getTestHeroes()[0];
|
||||
|
||||
function heroModuleSetup() {
|
||||
// #docregion setup-hero-module
|
||||
beforeEach(async () => {
|
||||
const routerSpy = createRouterSpy();
|
||||
|
||||
await TestBed
|
||||
.configureTestingModule({
|
||||
imports: [HeroModule],
|
||||
// #enddocregion setup-hero-module
|
||||
// declarations: [ HeroDetailComponent ], // NO! DOUBLE DECLARATION
|
||||
// #docregion setup-hero-module
|
||||
providers: [
|
||||
{provide: ActivatedRoute, useValue: activatedRoute},
|
||||
{provide: HeroService, useClass: TestHeroService},
|
||||
{provide: Router, useValue: routerSpy},
|
||||
provideRouter([
|
||||
{path: 'heroes/:id', component: HeroDetailComponent},
|
||||
{path: 'heroes', component: HeroListComponent},
|
||||
]),
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
]
|
||||
})
|
||||
.compileComponents();
|
||||
@@ -170,50 +144,35 @@ function heroModuleSetup() {
|
||||
|
||||
beforeEach(async () => {
|
||||
expectedHero = firstHero;
|
||||
activatedRoute.setParamMap({id: expectedHero.id});
|
||||
await createComponent();
|
||||
await createComponent(expectedHero.id);
|
||||
});
|
||||
|
||||
// #docregion selected-tests
|
||||
it("should display that hero's name", () => {
|
||||
it('should display that hero\'s name', () => {
|
||||
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
|
||||
});
|
||||
// #enddocregion route-good-id
|
||||
|
||||
it('should navigate when click cancel', () => {
|
||||
click(page.cancelBtn);
|
||||
expect(page.navigateSpy.calls.any())
|
||||
.withContext('router.navigate called')
|
||||
.toBe(true);
|
||||
expect(TestBed.inject(Router).url).toEqual(`/heroes/${expectedHero.id}`);
|
||||
});
|
||||
|
||||
it('should save when click save but not navigate immediately', () => {
|
||||
// Get service injected into component and spy on its`saveHero` method.
|
||||
// It delegates to fake `HeroService.updateHero` which delivers a safe test result.
|
||||
const hds = fixture.debugElement.injector.get(HeroDetailService);
|
||||
const saveSpy = spyOn(hds, 'saveHero').and.callThrough();
|
||||
|
||||
click(page.saveBtn);
|
||||
expect(saveSpy.calls.any())
|
||||
.withContext('HeroDetailService.save called')
|
||||
.toBe(true);
|
||||
expect(page.navigateSpy.calls.any())
|
||||
.withContext('router.navigate not called')
|
||||
.toBe(false);
|
||||
expect(TestBed.inject(HttpTestingController).expectOne({method: 'PUT', url: 'api/heroes'}));
|
||||
expect(TestBed.inject(Router).url).toEqual('/heroes/41');
|
||||
});
|
||||
|
||||
it('should navigate when click save and save resolves', fakeAsync(() => {
|
||||
click(page.saveBtn);
|
||||
tick(); // wait for async save to complete
|
||||
expect(page.navigateSpy.calls.any())
|
||||
.withContext('router.navigate called')
|
||||
.toBe(true);
|
||||
expect(TestBed.inject(Router).url).toEqual('/heroes/41');
|
||||
}));
|
||||
|
||||
// #docregion title-case-pipe
|
||||
it('should convert hero name to Title Case', () => {
|
||||
// get the name's input and display elements from the DOM
|
||||
const hostElement: HTMLElement = fixture.nativeElement;
|
||||
const hostElement: HTMLElement = harness.routeNativeElement!;
|
||||
const nameInput: HTMLInputElement = hostElement.querySelector('input')!;
|
||||
const nameDisplay: HTMLElement = hostElement.querySelector('span')!;
|
||||
|
||||
@@ -224,146 +183,97 @@ function heroModuleSetup() {
|
||||
nameInput.dispatchEvent(new Event('input'));
|
||||
|
||||
// Tell Angular to update the display binding through the title pipe
|
||||
fixture.detectChanges();
|
||||
harness.detectChanges();
|
||||
|
||||
expect(nameDisplay.textContent).toBe('Quick Brown Fox');
|
||||
});
|
||||
// #enddocregion title-case-pipe
|
||||
// #enddocregion selected-tests
|
||||
// #docregion route-good-id
|
||||
|
||||
// #enddocregion title-case-pipe
|
||||
});
|
||||
// #enddocregion route-good-id
|
||||
|
||||
// #docregion route-no-id
|
||||
describe('when navigate with no hero id', () => {
|
||||
beforeEach(async () => {
|
||||
await createComponent();
|
||||
});
|
||||
|
||||
it('should have hero.id === 0', () => {
|
||||
expect(component.hero.id).toBe(0);
|
||||
});
|
||||
|
||||
it('should display empty hero name', () => {
|
||||
expect(page.nameDisplay.textContent).toBe('');
|
||||
});
|
||||
});
|
||||
// #enddocregion route-no-id
|
||||
|
||||
// #docregion route-bad-id
|
||||
describe('when navigate to non-existent hero id', () => {
|
||||
beforeEach(async () => {
|
||||
activatedRoute.setParamMap({id: 99999});
|
||||
await createComponent();
|
||||
await createComponent(999);
|
||||
});
|
||||
|
||||
it('should try to navigate back to hero list', () => {
|
||||
expect(page.gotoListSpy.calls.any())
|
||||
.withContext('comp.gotoList called')
|
||||
.toBe(true);
|
||||
expect(page.navigateSpy.calls.any())
|
||||
.withContext('router.navigate called')
|
||||
.toBe(true);
|
||||
expect(TestBed.inject(Router).url).toEqual('/heroes');
|
||||
});
|
||||
});
|
||||
// #enddocregion route-bad-id
|
||||
|
||||
// Why we must use `fixture.debugElement.injector` in `Page()`
|
||||
it("cannot use `inject` to get component's provided HeroDetailService", () => {
|
||||
let service: HeroDetailService;
|
||||
fixture = TestBed.createComponent(HeroDetailComponent);
|
||||
expect(
|
||||
// Throws because `inject` only has access to TestBed's injector
|
||||
// which is an ancestor of the component's injector
|
||||
inject([HeroDetailService], (hds: HeroDetailService) => service = hds))
|
||||
.toThrowError(/No provider for HeroDetailService/);
|
||||
|
||||
// get `HeroDetailService` with component's own injector
|
||||
service = fixture.debugElement.injector.get(HeroDetailService);
|
||||
expect(service)
|
||||
.withContext('debugElement.injector')
|
||||
.toBeDefined();
|
||||
});
|
||||
}
|
||||
|
||||
/////////////////////
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { TitleCasePipe } from '../shared/title-case.pipe';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {TitleCasePipe} from '../shared/title-case.pipe';
|
||||
|
||||
function formsModuleSetup() {
|
||||
// #docregion setup-forms-module
|
||||
beforeEach(async () => {
|
||||
const routerSpy = createRouterSpy();
|
||||
|
||||
await TestBed
|
||||
.configureTestingModule({
|
||||
imports: [FormsModule],
|
||||
declarations: [HeroDetailComponent, TitleCasePipe],
|
||||
providers: [
|
||||
{provide: ActivatedRoute, useValue: activatedRoute},
|
||||
{provide: HeroService, useClass: TestHeroService},
|
||||
{provide: Router, useValue: routerSpy},
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]),
|
||||
]
|
||||
})
|
||||
.compileComponents();
|
||||
});
|
||||
// #enddocregion setup-forms-module
|
||||
|
||||
it("should display 1st hero's name", waitForAsync(() => {
|
||||
const expectedHero = firstHero;
|
||||
activatedRoute.setParamMap({id: expectedHero.id});
|
||||
createComponent().then(() => {
|
||||
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
|
||||
});
|
||||
}));
|
||||
it('should display 1st hero\'s name', async () => {
|
||||
const expectedHero = firstHero;
|
||||
await createComponent(expectedHero.id).then(() => {
|
||||
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
///////////////////////
|
||||
import { SharedModule } from '../shared/shared.module';
|
||||
|
||||
function sharedModuleSetup() {
|
||||
// #docregion setup-shared-module
|
||||
beforeEach(async () => {
|
||||
const routerSpy = createRouterSpy();
|
||||
|
||||
await TestBed
|
||||
.configureTestingModule({
|
||||
imports: [SharedModule],
|
||||
declarations: [HeroDetailComponent],
|
||||
providers: [
|
||||
{provide: ActivatedRoute, useValue: activatedRoute},
|
||||
{provide: HeroService, useClass: TestHeroService},
|
||||
{provide: Router, useValue: routerSpy},
|
||||
provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]),
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
]
|
||||
})
|
||||
.compileComponents();
|
||||
});
|
||||
// #enddocregion setup-shared-module
|
||||
|
||||
it("should display 1st hero's name", waitForAsync(() => {
|
||||
const expectedHero = firstHero;
|
||||
activatedRoute.setParamMap({id: expectedHero.id});
|
||||
createComponent().then(() => {
|
||||
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
|
||||
});
|
||||
}));
|
||||
it('should display 1st hero\'s name', async () => {
|
||||
const expectedHero = firstHero;
|
||||
await createComponent(expectedHero.id).then(() => {
|
||||
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/////////// Helpers /////
|
||||
|
||||
// #docregion create-component
|
||||
/** Create the HeroDetailComponent, initialize it, set test variables */
|
||||
function createComponent() {
|
||||
fixture = TestBed.createComponent(HeroDetailComponent);
|
||||
component = fixture.componentInstance;
|
||||
page = new Page(fixture);
|
||||
// #docregion create-component
|
||||
async function createComponent(id: number) {
|
||||
harness = await RouterTestingHarness.create();
|
||||
component = await harness.navigateByUrl(`/heroes/${id}`, HeroDetailComponent);
|
||||
page = new Page();
|
||||
|
||||
// 1st change detection triggers ngOnInit which gets a hero
|
||||
fixture.detectChanges();
|
||||
return fixture.whenStable().then(() => {
|
||||
// 2nd change detection displays the async-fetched hero
|
||||
fixture.detectChanges();
|
||||
});
|
||||
const request = TestBed.inject(HttpTestingController).expectOne(`api/heroes/?id=${id}`);
|
||||
const hero = getTestHeroes().find(h => h.id === Number(id));
|
||||
request.flush(hero ? [hero] : []);
|
||||
harness.detectChanges();
|
||||
}
|
||||
// #enddocregion create-component
|
||||
|
||||
@@ -386,30 +296,13 @@ class Page {
|
||||
return this.query<HTMLInputElement>('input');
|
||||
}
|
||||
|
||||
gotoListSpy: jasmine.Spy;
|
||||
navigateSpy: jasmine.Spy;
|
||||
|
||||
constructor(someFixture: ComponentFixture<HeroDetailComponent>) {
|
||||
// get the navigate spy from the injected router spy object
|
||||
const routerSpy = someFixture.debugElement.injector.get(Router) as any;
|
||||
this.navigateSpy = routerSpy.navigate;
|
||||
|
||||
// spy on component's `gotoList()` method
|
||||
const someComponent = someFixture.componentInstance;
|
||||
this.gotoListSpy = spyOn(someComponent, 'gotoList').and.callThrough();
|
||||
}
|
||||
|
||||
//// query helpers ////
|
||||
private query<T>(selector: string): T {
|
||||
return fixture.nativeElement.querySelector(selector);
|
||||
return harness.routeNativeElement!.querySelector(selector)! as T;
|
||||
}
|
||||
|
||||
private queryAll<T>(selector: string): T[] {
|
||||
return fixture.nativeElement.querySelectorAll(selector);
|
||||
return harness.routeNativeElement!.querySelectorAll(selector) as any as T[];
|
||||
}
|
||||
}
|
||||
// #enddocregion page
|
||||
|
||||
function createRouterSpy() {
|
||||
return jasmine.createSpyObj('Router', ['navigate']);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,29 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
import { Hero } from '../model/hero';
|
||||
import { HeroService } from '../model/hero.service';
|
||||
import {Hero} from '../model/hero';
|
||||
import {HeroService} from '../model/hero.service';
|
||||
|
||||
// #docregion prototype
|
||||
@Injectable()
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class HeroDetailService {
|
||||
constructor(private heroService: HeroService) { }
|
||||
// #enddocregion prototype
|
||||
constructor(private heroService: HeroService) {}
|
||||
// #enddocregion prototype
|
||||
|
||||
// Returns a clone which caller may modify safely
|
||||
getHero(id: number | string): Observable<Hero | null> {
|
||||
getHero(id: number|string): Observable<Hero|null> {
|
||||
if (typeof id === 'string') {
|
||||
id = parseInt(id, 10);
|
||||
}
|
||||
return this.heroService.getHero(id).pipe(
|
||||
map(hero => hero ? Object.assign({}, hero) : null) // clone or null
|
||||
map(hero => hero ? Object.assign({}, hero) : null) // clone or null
|
||||
);
|
||||
}
|
||||
|
||||
saveHero(hero: Hero) {
|
||||
return this.heroService.updateHero(hero);
|
||||
}
|
||||
// #docregion prototype
|
||||
// #docregion prototype
|
||||
}
|
||||
// #enddocregion prototype
|
||||
|
||||
@@ -1,74 +1,69 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
|
||||
import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs';
|
||||
import {catchError, map, tap} from 'rxjs/operators';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { catchError, map, tap } from 'rxjs/operators';
|
||||
|
||||
import { Hero } from './hero';
|
||||
import {Hero} from './hero';
|
||||
|
||||
const httpOptions = {
|
||||
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
|
||||
headers: new HttpHeaders({'Content-Type': 'application/json'})
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class HeroService {
|
||||
|
||||
readonly heroesUrl = 'api/heroes'; // URL to web api
|
||||
|
||||
constructor(private http: HttpClient) { }
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
/** GET heroes from the server */
|
||||
getHeroes(): Observable<Hero[]> {
|
||||
return this.http.get<Hero[]>(this.heroesUrl)
|
||||
.pipe(
|
||||
tap(heroes => this.log('fetched heroes')),
|
||||
catchError(this.handleError('getHeroes'))
|
||||
) as Observable<Hero[]>;
|
||||
.pipe(
|
||||
tap(heroes => this.log('fetched heroes')),
|
||||
catchError(this.handleError('getHeroes'))) as Observable<Hero[]>;
|
||||
}
|
||||
|
||||
/** GET hero by id. Return `undefined` when id not found */
|
||||
getHero<Data>(id: number | string): Observable<Hero> {
|
||||
getHero<Data>(id: number|string): Observable<Hero> {
|
||||
if (typeof id === 'string') {
|
||||
id = parseInt(id, 10);
|
||||
}
|
||||
const url = `${this.heroesUrl}/?id=${id}`;
|
||||
return this.http.get<Hero[]>(url)
|
||||
.pipe(
|
||||
map(heroes => heroes[0]), // returns a {0|1} element array
|
||||
return this.http.get<Hero[]>(url).pipe(
|
||||
map(heroes => heroes[0]), // returns a {0|1} element array
|
||||
tap(h => {
|
||||
const outcome = h ? 'fetched' : 'did not find';
|
||||
this.log(`${outcome} hero id=${id}`);
|
||||
}),
|
||||
catchError(this.handleError<Hero>(`getHero id=${id}`))
|
||||
);
|
||||
catchError(this.handleError<Hero>(`getHero id=${id}`)));
|
||||
}
|
||||
|
||||
//////// Save methods //////////
|
||||
|
||||
/** POST: add a new hero to the server */
|
||||
addHero(hero: Hero): Observable<Hero> {
|
||||
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
|
||||
tap((addedHero) => this.log(`added hero w/ id=${addedHero.id}`)),
|
||||
catchError(this.handleError<Hero>('addHero'))
|
||||
);
|
||||
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
|
||||
.pipe(
|
||||
tap((addedHero) => this.log(`added hero w/ id=${addedHero.id}`)),
|
||||
catchError(this.handleError<Hero>('addHero')));
|
||||
}
|
||||
/** DELETE: delete the hero from the server */
|
||||
deleteHero(hero: Hero | number): Observable<Hero> {
|
||||
deleteHero(hero: Hero|number): Observable<Hero> {
|
||||
const id = typeof hero === 'number' ? hero : hero.id;
|
||||
const url = `${this.heroesUrl}/${id}`;
|
||||
|
||||
return this.http.delete<Hero>(url, httpOptions).pipe(
|
||||
tap(_ => this.log(`deleted hero id=${id}`)),
|
||||
catchError(this.handleError<Hero>('deleteHero'))
|
||||
);
|
||||
return this.http.delete<Hero>(url, httpOptions)
|
||||
.pipe(
|
||||
tap(_ => this.log(`deleted hero id=${id}`)),
|
||||
catchError(this.handleError<Hero>('deleteHero')));
|
||||
}
|
||||
|
||||
/** PUT: update the hero on the server */
|
||||
updateHero(hero: Hero): Observable<any> {
|
||||
return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
|
||||
tap(_ => this.log(`updated hero id=${hero.id}`)),
|
||||
catchError(this.handleError<any>('updateHero'))
|
||||
);
|
||||
return this.http.put(this.heroesUrl, hero, httpOptions)
|
||||
.pipe(
|
||||
tap(_ => this.log(`updated hero id=${hero.id}`)),
|
||||
catchError(this.handleError<any>('updateHero')));
|
||||
}
|
||||
/**
|
||||
* Returns a function that handles Http operation failures.
|
||||
@@ -78,9 +73,8 @@ export class HeroService {
|
||||
*/
|
||||
private handleError<T>(operation = 'operation') {
|
||||
return (error: HttpErrorResponse): Observable<T> => {
|
||||
|
||||
// TODO: send the error to remote logging infrastructure
|
||||
console.error(error); // log to console instead
|
||||
console.error(error); // log to console instead
|
||||
|
||||
// If a native error is caught, do not transform it. We only want to
|
||||
// transform response errors that are not wrapped in an `Error`.
|
||||
@@ -92,7 +86,6 @@ export class HeroService {
|
||||
// TODO: better job of transforming error for user consumption
|
||||
throw new Error(`${operation} failed: ${message}`);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
private log(message: string) {
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
// export for convenience.
|
||||
export { ActivatedRoute } from '@angular/router';
|
||||
|
||||
// #docregion activated-route-stub
|
||||
import { convertToParamMap, ParamMap, Params } from '@angular/router';
|
||||
import { ReplaySubject } from 'rxjs';
|
||||
|
||||
/**
|
||||
* An ActivateRoute test double with a `paramMap` observable.
|
||||
* Use the `setParamMap()` method to add the next `paramMap` value.
|
||||
*/
|
||||
export class ActivatedRouteStub {
|
||||
// Use a ReplaySubject to share previous values with subscribers
|
||||
// and pump new values into the `paramMap` observable
|
||||
private subject = new ReplaySubject<ParamMap>();
|
||||
|
||||
constructor(initialParams?: Params) {
|
||||
this.setParamMap(initialParams);
|
||||
}
|
||||
|
||||
/** The mock paramMap observable */
|
||||
readonly paramMap = this.subject.asObservable();
|
||||
|
||||
/** Set the paramMap observable's next value */
|
||||
setParamMap(params: Params = {}) {
|
||||
this.subject.next(convertToParamMap(params));
|
||||
}
|
||||
}
|
||||
// #enddocregion activated-route-stub
|
||||
@@ -1,10 +1,8 @@
|
||||
import { DebugElement } from '@angular/core';
|
||||
import { tick, ComponentFixture } from '@angular/core/testing';
|
||||
import {DebugElement} from '@angular/core';
|
||||
import {ComponentFixture, tick} from '@angular/core/testing';
|
||||
|
||||
export * from './async-observable-helpers';
|
||||
export * from './activated-route-stub';
|
||||
export * from './jasmine-matchers';
|
||||
export * from './router-link-directive-stub';
|
||||
|
||||
///// Short utilities /////
|
||||
|
||||
@@ -18,12 +16,12 @@ export function advance(f: ComponentFixture<any>): void {
|
||||
// #docregion click-event
|
||||
/** Button events to pass to `DebugElement.triggerEventHandler` for RouterLink event handler */
|
||||
export const ButtonClickEvents = {
|
||||
left: { button: 0 },
|
||||
right: { button: 2 }
|
||||
left: {button: 0},
|
||||
right: {button: 2}
|
||||
};
|
||||
|
||||
/** Simulate element click. Defaults to mouse left-button click event. */
|
||||
export function click(el: DebugElement | HTMLElement, eventObj: any = ButtonClickEvents.left): void {
|
||||
export function click(el: DebugElement|HTMLElement, eventObj: any = ButtonClickEvents.left): void {
|
||||
if (el instanceof HTMLElement) {
|
||||
el.click();
|
||||
} else {
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { Directive, Input, HostListener } from '@angular/core';
|
||||
|
||||
// export for convenience.
|
||||
export { RouterLink} from '@angular/router';
|
||||
|
||||
/* eslint-disable @angular-eslint/directive-class-suffix, @angular-eslint/directive-selector */
|
||||
// #docregion router-link
|
||||
@Directive({
|
||||
selector: '[routerLink]'
|
||||
})
|
||||
export class RouterLinkDirectiveStub {
|
||||
@Input('routerLink') linkParams: any;
|
||||
navigatedTo: any = null;
|
||||
|
||||
@HostListener('click')
|
||||
onClick() {
|
||||
this.navigatedTo = this.linkParams;
|
||||
}
|
||||
}
|
||||
// #enddocregion router-link
|
||||
|
||||
/// Dummy module to satisfy Angular Language service. Never used.
|
||||
import { NgModule } from '@angular/core';
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
RouterLinkDirectiveStub
|
||||
]
|
||||
})
|
||||
export class RouterStubsModule {}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"tests": [
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
|
||||
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
@name Optional chain not nullable
|
||||
|
||||
@description
|
||||
|
||||
This diagnostic detects when the left side of an optional chain operation (`.?`) does not include `null` or `undefined` in its type in Angular templates.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
import {Component} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
template: `<div>{{ foo?.bar }}</div>`,
|
||||
// …
|
||||
})
|
||||
class MyComponent {
|
||||
// `foo` is declared as an object which *cannot* be `null` or `undefined`.
|
||||
foo: { bar: string} = { bar: 'bar'};
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
## What should I do instead?
|
||||
|
||||
Update the template and declared type to be in sync. Double-check the type of the input and confirm whether it is actually expected to be nullable.
|
||||
|
||||
If the input should be nullable, add `null` or `undefined` to its type to indicate this.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
import {Component} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
// If `foo` is nullish, `bar` won't be evaluated and the express will return the nullish value (`null` or `undefined`).
|
||||
template: `<div>{{ foo?.bar }}</div>`,
|
||||
// …
|
||||
})
|
||||
class MyComponent {
|
||||
foo: { bar: string} | null = { bar: 'bar'};
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
If the input should not be nullable, delete the `?` operator.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
import {Component} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
// Template always displays `bar` as `foo` is guaranteed to never be `null` or `undefined`
|
||||
template: `<div>{{ foo.bar }}</div>`,
|
||||
// …
|
||||
})
|
||||
class MyComponent {
|
||||
foo: { bar: string} = { bar: 'bar'};
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
## What if I can't avoid this?
|
||||
|
||||
This diagnostic can be disabled by editing the project's `tsconfig.json` file:
|
||||
|
||||
<code-example format="json" language="json">
|
||||
|
||||
{
|
||||
"angularCompilerOptions": {
|
||||
"extendedDiagnostics": {
|
||||
"checks": {
|
||||
"optionalChainNotNullable": "suppress"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
See [extended diagnostic configuration](extended-diagnostics#configuration) for more info.
|
||||
|
||||
<!-- links -->
|
||||
|
||||
<!-- external links -->
|
||||
|
||||
<!-- end links -->
|
||||
|
||||
@reviewed 2023-03-02
|
||||
@@ -11,9 +11,10 @@ Currently, Angular supports the following extended diagnostics:
|
||||
* [NG8101 - `invalidBananaInBox`](extended-diagnostics/NG8101)
|
||||
* [NG8102 - `nullishCoalescingNotNullable`](extended-diagnostics/NG8102)
|
||||
* [NG8103 - `missingControlFlowDirective`](extended-diagnostics/NG8103)
|
||||
* [NG8104 - `textAttributeNotBinding`](extended-diagnostics/NG8104)
|
||||
* [NG8105 - `missingNgForOfLet`](extended-diagnostics/NG8105)
|
||||
* [NG8106 - `suffixNotSupported`](extended-diagnostics/NG8106)
|
||||
* [NG8104 - `textAttributeNotBinding`](extended-diagnostics/NG8104)
|
||||
* [NG8107 - `optionalChainNotNullable`](extended-diagnostics/NG8107)
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ The following are some of the key AngularJS built-in directives and their equiva
|
||||
|
||||
| AngularJS | Angular |
|
||||
|:--- |:--- |
|
||||
| <header><code>ng-model</code></header> <code-example hideCopy format="html" language="html"> <input ng-model="vm.favoriteHero" /> </code-example> In AngularJS, the `ng-model` directive binds a form control to a property in the controller associated with the template. This provides **two-way binding** whereby changes result in the value in the view and the model being synchronized. | <header><code>ngModel</code></header> <code-example hideCopy path="ajs-quick-reference/src/app/movie-list.component.html" region="ngModel"></code-example> In Angular, **two-way binding** is indicatedr5t by `[()]`, descriptively referred to as a "banana in a box." This syntax is a shortcut for defining both:<ul><li>property binding, from the component to the view</li><li>event binding, from the view to the component</li></ul> thereby providing two-way binding. <br /> For more information on two-way binding with `ngModel`, see the [Displaying and updating properties with `ngModel`][AioGuideBuiltInDirectivesDisplayingAndUpdatingPropertiesWithNgmodel] section of [Built-in directives][AioGuideBuiltInDirectives]. |
|
||||
| <header><code>ng-model</code></header> <code-example hideCopy format="html" language="html"> <input ng-model="vm.favoriteHero" /> </code-example> In AngularJS, the `ng-model` directive binds a form control to a property in the controller associated with the template. This provides **two-way binding** whereby changes result in the value in the view and the model being synchronized. | <header><code>ngModel</code></header> <code-example hideCopy path="ajs-quick-reference/src/app/movie-list.component.html" region="ngModel"></code-example> In Angular, **two-way binding** is indicated by `[()]`, descriptively referred to as a "banana in a box." This syntax is a shortcut for defining both:<ul><li>property binding, from the component to the view</li><li>event binding, from the view to the component</li></ul> thereby providing two-way binding. <br /> For more information on two-way binding with `ngModel`, see the [Displaying and updating properties with `ngModel`][AioGuideBuiltInDirectivesDisplayingAndUpdatingPropertiesWithNgmodel] section of [Built-in directives][AioGuideBuiltInDirectives]. |
|
||||
|
||||
### `ng-repeat` → `*ngFor`
|
||||
|
||||
|
||||
@@ -220,7 +220,7 @@ When you use the Angular CLI command `ng new --strict`, it is set to `true` in t
|
||||
|
||||
When `true`, enables [strict template type checking](guide/template-typecheck#strict-mode).
|
||||
|
||||
The strictness flags that this open enables allow you to turn on and off specific types of strict template type checking.
|
||||
The strictness flags that this option enables allow you to turn on and off specific types of strict template type checking.
|
||||
See [troubleshooting template errors](guide/template-typecheck#troubleshooting-template-errors).
|
||||
|
||||
When you use the Angular CLI command `ng new --strict`, it is set to `true` in the new project's configuration.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Resolving zone pollution
|
||||
|
||||
**Zone.js** is a signaling mechanism that Angular uses to detect when an application state might have changed. It captures asynchronous operations like `setTimeout`, network requests, and event listeners. Angular schedules change detection based on signals from Zone.js
|
||||
**Zone.js** is a signaling mechanism that Angular uses to detect when an application state might have changed. It captures asynchronous operations like `setTimeout`, network requests, and event listeners. Angular schedules change detection based on signals from Zone.js.
|
||||
|
||||
In some cases scheduled [tasks](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide#tasks) or [microtasks](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide#microtasks) don’t make any changes in the data model, which makes running change detection unnecessary. Common examples are:
|
||||
* `requestAnimationFrame`, `setTimeout` or `setInterval`
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Change detection** is the process through which Angular checks to see whether your application state has changed, and if any DOM needs to be updated. At a high level, Angular walks your components from top to bottom, looking for changes. Angular runs its change detection mechanism periodically so that changes to the data model are reflected in an application’s view. Change detection can be triggered either manually or through an asynchronous event (for example, a user interaction or an XMLHttpRequest completion).
|
||||
|
||||
Change detection is a highly optimized performant, but it can still cause slowdowns if the application runs it too frequently.
|
||||
Change detection is highly optimized and performant, but it can still cause slowdowns if the application runs it too frequently.
|
||||
|
||||
In this guide, you’ll learn how to control and optimize the change detection mechanism by skipping parts of your application and running change detection only when necessary.
|
||||
|
||||
|
||||
@@ -247,7 +247,7 @@ The `production` configuration engages the following build optimization features
|
||||
| Features | Details |
|
||||
|:--- |:--- |
|
||||
| [Ahead-of-Time (AOT) Compilation](guide/aot-compiler) | Pre-compiles Angular component templates. |
|
||||
| [Production mode](#enable-prod-mode) | Deploys the production environment which enables *production mode*. |
|
||||
| [Production mode](#prod-mode) | Optimizes the application for the best runtime performance |
|
||||
| Bundling | Concatenates your many application and library files into a few bundles. |
|
||||
| Minification | Removes excess whitespace, comments, and optional tokens. |
|
||||
| Uglification | Rewrites code to use short, cryptic variable and function names. |
|
||||
@@ -255,23 +255,20 @@ The `production` configuration engages the following build optimization features
|
||||
|
||||
See [`ng build`](cli/build) for more about CLI build options and what they do.
|
||||
|
||||
<a id="enable-prod-mode"></a>
|
||||
<a id="prod-mode"></a>
|
||||
|
||||
### Enable runtime production mode
|
||||
### Production mode at runtime
|
||||
|
||||
In addition to build optimizations, Angular also has a runtime production mode.
|
||||
Angular applications run in development mode by default, as you can see by the following message on the browser console:
|
||||
When you run an application locally using `ng serve`, Angular uses the development mode configuration
|
||||
at runtime. The development mode at runtime enables extra safety checks, more detailed error messages
|
||||
and debugging utilities, such as the [expression-changed-after-checked](errors/NG0100) detection. Angular outputs
|
||||
a message in the browser console to indicate that the development mode is enabled.
|
||||
|
||||
<code-example format="output" hideCopy language="shell">
|
||||
Those extra checks are helpful during the development, but they require an extra code in a bundle, which is
|
||||
undesirable in production. To ensure that there are no implications on the bundle size, the build optimizer
|
||||
removes the development-only code from the bundle when building in production mode.
|
||||
|
||||
Angular is running in development mode.
|
||||
Call `enableProdMode()` to enable production mode.
|
||||
|
||||
</code-example>
|
||||
|
||||
*Production mode* improves application performance by disabling development-only safety checks and debugging utilities, such as the expression-changed-after-checked detection.
|
||||
Building your application with the production configuration automatically enables Angular's runtime production mode.
|
||||
|
||||
<a id="lazy-loading"></a>
|
||||
|
||||
### Lazy loading
|
||||
|
||||
@@ -45,7 +45,6 @@ v15 - v18
|
||||
| `@angular/common` | [`ReflectiveInjector`](#reflectiveinjector) | v8 | v11 |
|
||||
| `@angular/core` | [`DefaultIterableDiffer`](#core) | v7 | v11 |
|
||||
| `@angular/core` | [`ReflectiveKey`](#core) | v8 | v11 |
|
||||
| `@angular/core` | [`RenderComponentType`](#core) | v7 | v11 |
|
||||
| `@angular/core` | [`defineInjectable`](#core) | v8 | v11 |
|
||||
| `@angular/core` | [`entryComponents`](api/core/NgModule#entryComponents) | v9 | v11 |
|
||||
| `@angular/core` | [`ANALYZE_FOR_ENTRY_COMPONENTS`](api/core/ANALYZE_FOR_ENTRY_COMPONENTS) | v9 | v11 |
|
||||
@@ -274,14 +273,6 @@ In the [API reference section](api) of this site, deprecated APIs are indicated
|
||||
This section lists all deprecated features, which includes template syntax, configuration options, and any other deprecations not listed in the [Deprecated APIs](#deprecated-apis) section.
|
||||
It also includes deprecated API usage scenarios or API combinations, to augment the information above.
|
||||
|
||||
<a id="bazelbuilder"></a>
|
||||
|
||||
### Bazel builder and schematics
|
||||
|
||||
Bazel builder and schematics were introduced in Angular Labs to let users try out Bazel without having to manage Bazel version and BUILD files.
|
||||
This feature has been deprecated.
|
||||
For more information, please refer to the [migration doc](https://github.com/angular/angular/blob/main/packages/bazel/docs/BAZEL_SCHEMATICS.md).
|
||||
|
||||
<a id="wtf"></a>
|
||||
|
||||
### Web Tracing Framework integration
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# DevTools Overview
|
||||
|
||||
Angular DevTools is a browser extension that provides debugging and profiling capabilities for Angular applications.
|
||||
Angular DevTools supports Angular v12 and later.
|
||||
Angular DevTools supports Angular v12 and later when compiled with the [optimization configuration option](guide/workspace-config#optimization-configuration) disabled (<code>{optimization:false}</code>).
|
||||
|
||||
<div class="video-container">
|
||||
|
||||
|
||||
@@ -929,7 +929,7 @@ View Engine was deprecated in version 9 and removed in version 13.
|
||||
## view hierarchy
|
||||
|
||||
A tree of related views that can be acted on as a unit.
|
||||
The root view referenced as the *host view* of a component.
|
||||
The root view is referenced as the *host view* of a component.
|
||||
A host view is the root of a tree of *embedded views*, collected in a `ViewContainerRef` view container attached to an anchor element in the hosting component.
|
||||
The view hierarchy is a key part of Angular [change detection][AioGuideGlossaryChangeDetection].
|
||||
|
||||
|
||||
@@ -741,7 +741,7 @@ The example application uses `@Optional()` so the application does not throw an
|
||||
The `<app-child>` currently provides the `AnimalService` in the `viewProviders` array with the value of dog <code>🐶</code>.
|
||||
Because the injector has only to look at the `ElementInjector` of the `<app-child>` for the `AnimalService`, it never sees the whale <code>🐳</code>.
|
||||
|
||||
As in the `FlowerService` example, if you add `@SkipSelf()` to the constructor for the `AnimalService`, the injector won't look in the `ElementInjector` or the current `<app-child>` for the `AnimalService`.
|
||||
As in the `FlowerService` example, if you add `@SkipSelf()` to the constructor for the `AnimalService`, the injector won't look in the `ElementInjector` of the current `<app-child>` for the `AnimalService`.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
|
||||
@@ -1,3 +1,37 @@
|
||||
# Configure HTTP URL parameters
|
||||
# HTTP - Configure URL parameters
|
||||
|
||||
@reviewed 2022-10-06
|
||||
Use the `HttpParams` class with the `params` request option to add URL query strings in your `HttpRequest`.
|
||||
|
||||
## Create URL parameter using the search method
|
||||
|
||||
The following example, the `searchHeroes()` method queries for heroes whose names contain the search term.
|
||||
|
||||
Start by importing `HttpParams` class.
|
||||
|
||||
<code-example hideCopy language="typescript">
|
||||
|
||||
import {HttpParams} from "@angular/common/http";
|
||||
|
||||
</code-example>
|
||||
|
||||
<code-example linenums="false" path="http/src/app/heroes/heroes.service.ts" region="searchHeroes"></code-example>
|
||||
|
||||
If there is a search term, the code constructs an options object with an HTML URL-encoded search parameter.
|
||||
If the term is "cat", for example, the GET request URL would be `api/heroes?name=cat`.
|
||||
|
||||
The `HttpParams` object is immutable.
|
||||
If you need to update the options, save the returned value of the `.set()` method.
|
||||
|
||||
## Create URL parameters from a query
|
||||
|
||||
You can also create HTTP parameters directly from a query string by using the `fromString` variable:
|
||||
|
||||
<code-example hideCopy language="typescript">
|
||||
|
||||
const params = new HttpParams({fromString: 'name=foo'});
|
||||
|
||||
</code-example>
|
||||
|
||||
<a id="intercepting-requests-and-responses"></a>
|
||||
|
||||
@reviewed 2022-11-08
|
||||
|
||||
@@ -1,3 +1,60 @@
|
||||
# Handle request errors
|
||||
# HTTP client - Handle request errors
|
||||
|
||||
@reviewed 2022-10-06
|
||||
If the request fails on the server, `HttpClient` returns an *error* object instead of a successful response.
|
||||
|
||||
The same service that performs your server transactions should also perform error inspection, interpretation, and resolution.
|
||||
|
||||
When an error occurs, you can obtain details of what failed to inform your user.
|
||||
In some cases, you might also automatically [retry the request](#retry).
|
||||
|
||||
<a id="error-details"></a>
|
||||
|
||||
## Getting error details
|
||||
|
||||
An app should give the user useful feedback when data access fails.
|
||||
A raw error object is not particularly useful as feedback.
|
||||
In addition to detecting that an error has occurred, you need to get error details and use those details to compose a user-friendly response.
|
||||
|
||||
Two types of errors can occur.
|
||||
|
||||
* The server backend might reject the request, returning an HTTP response with a status code such as 404 or 500.
|
||||
These are error *responses*.
|
||||
|
||||
* Something could go wrong on the client-side such as a network error that prevents the request from completing successfully or an exception thrown in an RxJS operator.
|
||||
These errors have `status` set to `0` and the `error` property contains a `ProgressEvent` object, whose `type` might provide further information.
|
||||
|
||||
`HttpClient` captures both kinds of errors in its `HttpErrorResponse`.
|
||||
Inspect that response to identify the error's cause.
|
||||
|
||||
The following example defines an error handler in the previously defined ConfigService.
|
||||
|
||||
<code-example header="app/config/config.service.ts (handleError)" path="http/src/app/config/config.service.ts" region="handleError"></code-example>
|
||||
|
||||
The handler returns an RxJS `ErrorObservable` with a user-friendly error message.
|
||||
The following code updates the `getConfig()` method, using a [pipe](guide/pipes "Pipes guide") to send all observables returned by the `HttpClient.get()` call to the error handler.
|
||||
|
||||
<code-example header="app/config/config.service.ts (getConfig v.3 with error handler)" path="http/src/app/config/config.service.ts" region="getConfig_3"></code-example>
|
||||
|
||||
<a id="retry"></a>
|
||||
|
||||
## Retrying a failed request
|
||||
|
||||
Sometimes the error is transient and goes away automatically if you try again.
|
||||
For example, network interruptions are common in mobile scenarios, and trying again can produce a successful result.
|
||||
|
||||
The [RxJS library](guide/rx-library) offers several *retry* operators.
|
||||
For example, the `retry()` operator automatically re-subscribes to a failed `Observable` a specified number of times.
|
||||
*Re-subscribing* to the result of an `HttpClient` method call has the effect of reissuing the HTTP request.
|
||||
|
||||
The following example shows how to pipe a failed request to the `retry()` operator before passing it to the error handler.
|
||||
|
||||
<code-example header="app/config/config.service.ts (getConfig with retry)" path="http/src/app/config/config.service.ts" region="getConfig"></code-example>
|
||||
|
||||
## Sending data to a server
|
||||
|
||||
In addition to fetching data from a server, `HttpClient` supports other HTTP methods such as PUT, POST, and DELETE, which you can use to modify the remote data.
|
||||
|
||||
The sample app for this guide includes an abridged version of the "Tour of Heroes" example that fetches heroes and enables users to add, delete, and update them.
|
||||
The following sections show examples of the data-update methods from the sample's `HeroesService`.
|
||||
|
||||
@reviewed 2023-02-27
|
||||
|
||||
@@ -1,3 +1,189 @@
|
||||
# Intercept requests and responses
|
||||
# HTTP - Intercept requests and responses
|
||||
|
||||
@reviewed 2022-10-06
|
||||
With interception, you declare *interceptors* that inspect and transform HTTP requests from your application to a server.
|
||||
The same interceptors can also inspect and transform a server's responses on their way back to the application.
|
||||
Multiple interceptors form a *forward-and-backward* chain of request/response handlers.
|
||||
|
||||
Interceptors can perform a variety of *implicit* tasks, from authentication to logging, in a routine, standard way, for every HTTP request/response.
|
||||
|
||||
Without interception, developers would have to implement these tasks *explicitly* for each `HttpClient` method call.
|
||||
|
||||
## Write an interceptor
|
||||
|
||||
To implement an interceptor, declare a class that implements the `intercept()` method of the `HttpInterceptor` interface.
|
||||
|
||||
Here is a do-nothing `noop` interceptor that passes the request through without touching it:
|
||||
|
||||
<code-example header="app/http-interceptors/noop-interceptor.ts" path="http/src/app/http-interceptors/noop-interceptor.ts"></code-example>
|
||||
|
||||
The `intercept` method transforms a request into an `Observable` that eventually returns the HTTP response.
|
||||
In this sense, each interceptor is fully capable of handling the request entirely by itself.
|
||||
|
||||
Most interceptors inspect the request on the way in and forward the potentially altered request to the `handle()` method of the `next` object which implements the [`HttpHandler`](api/common/http/HttpHandler) interface.
|
||||
|
||||
<code-example format="javascript" language="javascript">
|
||||
|
||||
export abstract class HttpHandler {
|
||||
abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>;
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
Like `intercept()`, the `handle()` method transforms an HTTP request into an `Observable` of [`HttpEvents`](#interceptor-events) which ultimately include the server's response.
|
||||
The `intercept()` method could inspect that observable and alter it before returning it to the caller.
|
||||
|
||||
This `no-op` interceptor calls `next.handle()` with the original request and returns the observable without doing a thing.
|
||||
|
||||
## The `next` object
|
||||
|
||||
The `next` object represents the next interceptor in the chain of interceptors.
|
||||
The final `next` in the chain is the `HttpClient` backend handler that sends the request to the server and receives the server's response.
|
||||
|
||||
Most interceptors call `next.handle()` so that the request flows through to the next interceptor and, eventually, the backend handler.
|
||||
An interceptor *could* skip calling `next.handle()`, short-circuit the chain, and [return its own `Observable`](guide/http-interceptor-use-cases#caching) with an artificial server response.
|
||||
|
||||
This is a common middleware pattern found in frameworks such as Express.js.
|
||||
|
||||
## Provide the interceptor
|
||||
|
||||
The `NoopInterceptor` is a service managed by Angular's [dependency injection (DI)](guide/dependency-injection) system.
|
||||
Like other services, you must provide the interceptor class before the app can use it.
|
||||
|
||||
Because interceptors are optional dependencies of the `HttpClient` service, you must provide them in the same injector or a parent of the injector that provides `HttpClient`.
|
||||
Interceptors provided *after* DI creates the `HttpClient` are ignored.
|
||||
|
||||
This app provides `HttpClient` in the app's root injector, as a side-effect of importing the `HttpClientModule` in `AppModule`.
|
||||
You should provide interceptors in `AppModule` as well.
|
||||
|
||||
After importing the `HTTP_INTERCEPTORS` injection token from `@angular/common/http`, write the `NoopInterceptor` provider like this:
|
||||
|
||||
<code-example path="http/src/app/http-interceptors/index.ts" region="noop-provider"></code-example>
|
||||
|
||||
Notice the `multi: true` option.
|
||||
This required setting tells Angular that `HTTP_INTERCEPTORS` is a token for a *multiprovider* that injects an array of values, rather than a single value.
|
||||
|
||||
You *could* add this provider directly to the providers array of the `AppModule`.
|
||||
However, it's rather verbose and there's a good chance that you'll create more interceptors and provide them in the same way.
|
||||
You must also pay [close attention to the order](#interceptor-order) in which you provide these interceptors.
|
||||
|
||||
Consider creating a "barrel" file that gathers all the interceptor providers into an `httpInterceptorProviders` array, starting with this first one, the `NoopInterceptor`.
|
||||
|
||||
<code-example header="app/http-interceptors/index.ts" path="http/src/app/http-interceptors/index.ts" region="interceptor-providers"></code-example>
|
||||
|
||||
Then import and add it to the `AppModule` `providers array` like this:
|
||||
|
||||
<code-example header="app/app.module.ts (interceptor providers)" path="http/src/app/app.module.ts" region="interceptor-providers"></code-example>
|
||||
|
||||
As you create new interceptors, add them to the `httpInterceptorProviders` array and you won't have to revisit the `AppModule`.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
There are many more interceptors in the complete sample code.
|
||||
|
||||
</div>
|
||||
|
||||
## Interceptor order
|
||||
|
||||
Angular applies interceptors in the order that you provide them.
|
||||
For example, consider a situation in which you want to handle the authentication of your HTTP requests and log them before sending them to a server.
|
||||
To accomplish this task, you could provide an `AuthInterceptor` service and then a `LoggingInterceptor` service.
|
||||
Outgoing requests would flow from the `AuthInterceptor` to the `LoggingInterceptor`.
|
||||
Responses from these requests would flow in the other direction, from `LoggingInterceptor` back to `AuthInterceptor`.
|
||||
The following is a visual representation of the process:
|
||||
|
||||
<div class="lightbox">
|
||||
|
||||
<img alt="Interceptor in order of HttpClient, AuthInterceptor, AuthInterceptor, HttpBackend, Server, and back in opposite order to show the two-way flow" src="generated/images/guide/http/interceptor-order.svg">
|
||||
|
||||
</div>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The last interceptor in the process is always the `HttpBackend` that handles communication with the server.
|
||||
|
||||
</div>
|
||||
|
||||
You cannot change the order or remove interceptors later.
|
||||
If you need to enable and disable an interceptor dynamically, you'll have to build that capability into the interceptor itself.
|
||||
|
||||
<a id="interceptor-events"></a>
|
||||
|
||||
## Handle interceptor events
|
||||
|
||||
Most `HttpClient` methods return observables of `HttpResponse<any>`.
|
||||
The `HttpResponse` class itself is actually an event, whose type is `HttpEventType.Response`.
|
||||
A single HTTP request can, however, generate multiple events of other types, including upload and download progress events.
|
||||
The methods `HttpInterceptor.intercept()` and `HttpHandler.handle()` return observables of `HttpEvent<any>`.
|
||||
|
||||
Many interceptors are only concerned with the outgoing request and return the event stream from `next.handle()` without modifying it.
|
||||
Some interceptors, however, need to examine and modify the response from `next.handle()`; these operations can see all of these events in the stream.
|
||||
|
||||
<a id="immutability"></a>
|
||||
|
||||
Although interceptors are capable of modifying requests and responses, the `HttpRequest` and `HttpResponse` instance properties are `readonly`, rendering them largely immutable.
|
||||
They are immutable for a good reason:
|
||||
An app might retry a request several times before it succeeds, which means that the interceptor chain can re-process the same request multiple times.
|
||||
If an interceptor could modify the original request object, the re-tried operation would start from the modified request rather than the original.
|
||||
Immutability ensures that interceptors see the same request for each try.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Your interceptor should return every event without modification unless it has a compelling reason to do otherwise.
|
||||
|
||||
</div>
|
||||
|
||||
TypeScript prevents you from setting `HttpRequest` read-only properties.
|
||||
|
||||
<code-example format="javascript" language="javascript">
|
||||
|
||||
// Typescript disallows the following assignment because req.url is readonly
|
||||
req.url = req.url.replace('http://', 'https://');
|
||||
|
||||
</code-example>
|
||||
|
||||
If you must alter a request, clone it first and modify the clone before passing it to `next.handle()`.
|
||||
You can clone and modify the request in a single step, as shown in the following example.
|
||||
|
||||
<code-example header="app/http-interceptors/ensure-https-interceptor.ts (excerpt)" path="http/src/app/http-interceptors/ensure-https-interceptor.ts" region="excerpt"></code-example>
|
||||
|
||||
The `clone()` method's hash argument lets you mutate specific properties of the request while copying the others.
|
||||
|
||||
### Modify a request body
|
||||
|
||||
The `readonly` assignment guard can't prevent deep updates and, in particular, it can't prevent you from modifying a property of a request body object.
|
||||
|
||||
<code-example format="javascript" language="javascript">
|
||||
|
||||
req.body.name = req.body.name.trim(); // bad idea!
|
||||
|
||||
</code-example>
|
||||
|
||||
If you must modify the request body, follow these steps.
|
||||
|
||||
1. Copy the body and make your change in the copy.
|
||||
1. Clone the request object, using its `clone()` method.
|
||||
1. Replace the clone's body with the modified copy.
|
||||
|
||||
<code-example header="app/http-interceptors/trim-name-interceptor.ts (excerpt)" path="http/src/app/http-interceptors/trim-name-interceptor.ts" region="excerpt"></code-example>
|
||||
|
||||
### Clear the request body in a clone
|
||||
|
||||
Sometimes you need to clear the request body rather than replace it.
|
||||
To do this, set the cloned request body to `null`.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**TIP**: <br />
|
||||
If you set the cloned request body to `undefined`, Angular assumes you intend to leave the body as is.
|
||||
|
||||
</div>
|
||||
|
||||
<code-example format="javascript" language="javascript">
|
||||
|
||||
newReq = req.clone({ … }); // body not mentioned => preserve original body
|
||||
newReq = req.clone({ body: undefined }); // preserve original body
|
||||
newReq = req.clone({ body: null }); // clear the body
|
||||
|
||||
</code-example>
|
||||
|
||||
@reviewed 2023-03-16
|
||||
|
||||
@@ -1,3 +1,127 @@
|
||||
# HTTP interceptor use-cases
|
||||
# HTTP - interceptor use-cases
|
||||
|
||||
@reviewed 2022-10-06
|
||||
Following are a number of common uses for interceptors.
|
||||
|
||||
## Set default headers
|
||||
|
||||
Apps often use an interceptor to set default headers on outgoing requests.
|
||||
|
||||
The sample app has an `AuthService` that produces an authorization token.
|
||||
Here is its `AuthInterceptor` that injects that service to get the token and adds an authorization header with that token to every outgoing request:
|
||||
|
||||
<code-example header="app/http-interceptors/auth-interceptor.ts" path="http/src/app/http-interceptors/auth-interceptor.ts"></code-example>
|
||||
|
||||
The practice of cloning a request to set new headers is so common that there's a `setHeaders` shortcut for it:
|
||||
|
||||
<code-example path="http/src/app/http-interceptors/auth-interceptor.ts" region="set-header-shortcut"></code-example>
|
||||
|
||||
An interceptor that alters headers can be used for a number of different operations, including:
|
||||
|
||||
* Authentication/authorization
|
||||
* Caching behavior; for example, `If-Modified-Since`
|
||||
* XSRF protection
|
||||
|
||||
## Log request and response pairs
|
||||
|
||||
Because interceptors can process the request and response *together*, they can perform tasks such as timing and logging an entire HTTP operation.
|
||||
|
||||
Consider the following `LoggingInterceptor`, which captures the time of the request,
|
||||
the time of the response, and logs the outcome with the elapsed time
|
||||
with the injected `MessageService`.
|
||||
|
||||
<code-example header="app/http-interceptors/logging-interceptor.ts)" path="http/src/app/http-interceptors/logging-interceptor.ts" region="excerpt"></code-example>
|
||||
|
||||
The RxJS `tap` operator captures whether the request succeeded or failed.
|
||||
The RxJS `finalize` operator is called when the response observable either returns an error or completes and reports the outcome to the `MessageService`.
|
||||
|
||||
Neither `tap` nor `finalize` touch the values of the observable stream returned to the caller.
|
||||
|
||||
<a id="custom-json-parser"></a>
|
||||
|
||||
## Custom JSON parsing
|
||||
|
||||
Interceptors can be used to replace the built-in JSON parsing with a custom implementation.
|
||||
|
||||
The `CustomJsonInterceptor` in the following example demonstrates how to achieve this.
|
||||
If the intercepted request expects a `'json'` response, the `responseType` is changed to `'text'` to disable the built-in JSON parsing.
|
||||
Then the response is parsed via the injected `JsonParser`.
|
||||
|
||||
<code-example header="app/http-interceptors/custom-json-interceptor.ts" path="http/src/app/http-interceptors/custom-json-interceptor.ts" region="custom-json-interceptor"></code-example>
|
||||
|
||||
You can then implement your own custom `JsonParser`.
|
||||
Here is a custom JsonParser that has a special date reviver.
|
||||
|
||||
<code-example header="app/http-interceptors/custom-json-interceptor.ts" path="http/src/app/http-interceptors/custom-json-interceptor.ts" region="custom-json-parser"></code-example>
|
||||
|
||||
You provide the `CustomParser` along with the `CustomJsonInterceptor`.
|
||||
|
||||
<code-example header="app/http-interceptors/index.ts" path="http/src/app/http-interceptors/index.ts" region="custom-json-interceptor"></code-example>
|
||||
|
||||
<a id="caching"></a>
|
||||
|
||||
## Cache requests
|
||||
|
||||
Interceptors can handle requests by themselves, without forwarding to `next.handle()`.
|
||||
|
||||
For example, you might decide to cache certain requests and responses to improve performance.
|
||||
You can delegate caching to an interceptor without disturbing your existing data services.
|
||||
|
||||
The `CachingInterceptor` in the following example demonstrates this approach.
|
||||
|
||||
<code-example header="app/http-interceptors/caching-interceptor.ts)" path="http/src/app/http-interceptors/caching-interceptor.ts" region="v1"></code-example>
|
||||
|
||||
* The `isCacheable()` function determines if the request is cacheable.
|
||||
In this sample, only GET requests to the package search API are cacheable.
|
||||
|
||||
* If the request is not cacheable, the interceptor forwards the request to the next handler in the chain
|
||||
* If a cacheable request is found in the cache, the interceptor returns an `of()` *observable* with the cached response, by-passing the `next` handler and all other interceptors downstream
|
||||
* If a cacheable request is not in cache, the code calls `sendRequest()`.
|
||||
This function forwards the request to `next.handle()` which ultimately calls the server and returns the server's response.
|
||||
|
||||
<a id="send-request"></a>
|
||||
|
||||
<code-example path="http/src/app/http-interceptors/caching-interceptor.ts" region="send-request"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Notice how `sendRequest()` intercepts the response on its way back to the application.
|
||||
This method pipes the response through the `tap()` operator, whose callback adds the response to the cache.
|
||||
|
||||
The original response continues untouched back up through the chain of interceptors to the application caller.
|
||||
|
||||
Data services, such as `PackageSearchService`, are unaware that some of their `HttpClient` requests actually return cached responses.
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<a id="cache-refresh"></a>
|
||||
|
||||
## Use interceptors to request multiple values
|
||||
|
||||
The `HttpClient.get()` method normally returns an observable that emits a single value, either the data or an error.
|
||||
An interceptor can change this to an observable that emits [multiple values](guide/observables).
|
||||
|
||||
The following revised version of the `CachingInterceptor` optionally returns an observable that immediately emits the cached response, sends the request on to the package search API, and emits again later with the updated search results.
|
||||
|
||||
<code-example path="http/src/app/http-interceptors/caching-interceptor.ts" region="intercept-refresh"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The *cache-then-refresh* option is triggered by the presence of a custom `x-refresh` header.
|
||||
|
||||
A checkbox on the `PackageSearchComponent` toggles a `withRefresh` flag, which is one of the arguments to `PackageSearchService.search()`.
|
||||
That `search()` method creates the custom `x-refresh` header and adds it to the request before calling `HttpClient.get()`.
|
||||
|
||||
</div>
|
||||
|
||||
The revised `CachingInterceptor` sets up a server request whether there's a cached value or not, using the same `sendRequest()` method described [above](#send-request).
|
||||
The `results$` observable makes the request when subscribed.
|
||||
|
||||
* If there's no cached value, the interceptor returns `results$`.
|
||||
* If there is a cached value, the code *pipes* the cached response onto `results$`. This produces a recomposed observable that emits two responses, so subscribers will see a sequence of these two responses:
|
||||
* The cached response that's emitted immediately
|
||||
* The response from the server, that's emitted later
|
||||
|
||||
<a id="report-progress"></a>
|
||||
|
||||
@reviewed 2022-11-08
|
||||
|
||||
@@ -1,3 +1,47 @@
|
||||
# Make a JSON with Padding request
|
||||
# HTTP: Make a JSONP request
|
||||
|
||||
@reviewed 2022-10-06
|
||||
“JSON with Padding” (JSONP) is a method to deceive a web browser into carrying out requests with a `<script>` tag that uses the SRC attribute to make a special API request.
|
||||
|
||||
Apps can use the `HttpClient` to make [JSONP](https://en.wikipedia.org/wiki/JSONP) requests across domains when a server doesn't support [CORS protocol](https://developer.mozilla.org/docs/Web/HTTP/CORS).
|
||||
|
||||
Angular JSONP requests return an `Observable`.
|
||||
Follow the pattern for subscribing to observables and use the RxJS `map` operator to transform the response before using the [async pipe](api/common/AsyncPipe) to manage the results.
|
||||
|
||||
In Angular, use JSONP by including `HttpClientJsonpModule` in the `NgModule` imports.
|
||||
In the following example, the `searchHeroes()` method uses a JSONP request to query for heroes whose names contain the search term.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
/* GET heroes whose name contains search term */
|
||||
searchHeroes(term: string): Observable {
|
||||
term = term.trim();
|
||||
|
||||
const heroesURL = `${this.heroesURL}?${term}`;
|
||||
return this.http.jsonp(heroesUrl, 'callback').pipe(
|
||||
catchError(this.handleError('searchHeroes', [])) // then handle the error
|
||||
);
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
This request passes the `heroesURL` as the first parameter and the callback function name as the second parameter.
|
||||
The response is wrapped in the callback function, which takes the observables returned by the JSONP method and pipes them through to the error handler.
|
||||
|
||||
## Request non-JSON data
|
||||
|
||||
Not all APIs return JSON data.
|
||||
In this next example, a `DownloaderService` method reads a text file from the server and logs the file contents, before returning those contents to the caller as an `Observable<string>`.
|
||||
|
||||
<code-example header="app/downloader/downloader.service.ts (getTextFile)" linenums="false" path="http/src/app/downloader/downloader.service.ts" region="getTextFile"></code-example>
|
||||
|
||||
`HttpClient.get()` returns a string rather than the default JSON because of the `responseType` option.
|
||||
|
||||
The RxJS `tap` operator lets the code inspect both success and error values passing through the observable without disturbing them.
|
||||
|
||||
A `download()` method in the `DownloaderComponent` initiates the request by subscribing to the service method.
|
||||
|
||||
<code-example header="app/downloader/downloader.component.ts (download)" linenums="false" path="http/src/app/downloader/downloader.component.ts" region="download"></code-example>
|
||||
|
||||
<a id="error-handling"></a>
|
||||
|
||||
@reviewed 2022-11-03
|
||||
|
||||
@@ -1,3 +1,65 @@
|
||||
# Optimize server interaction with debouncing
|
||||
# HTTP - Optimize server interaction with debouncing
|
||||
|
||||
@reviewed 2022-10-06
|
||||
If you need to make an HTTP request in response to user input, it's not efficient to send a request for every keystroke. It's better to wait until the user stops typing and then send a request. This technique is known as debouncing.
|
||||
|
||||
## Implement debouncing
|
||||
|
||||
Consider the following template, which lets a user enter a search term to find a package by name. When the user enters a name in a search-box, the `PackageSearchComponent` sends a search request for a package with that name to the package search API.
|
||||
|
||||
<code-example header="app/package-search/package-search.component.html (search)" path="http/src/app/package-search/package-search.component.html" region="search"></code-example>
|
||||
|
||||
Here, the `keyup` event binding sends every keystroke to the component's `search()` method.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The type of `$event.target` is only `EventTarget` in the template.
|
||||
In the `getValue()` method, the target is cast to an `HTMLInputElement` to let type-safe have access to its `value` property.
|
||||
|
||||
<code-example path="http/src/app/package-search/package-search.component.ts" region="getValue"></code-example>
|
||||
|
||||
</div>
|
||||
|
||||
The following snippet implements debouncing for this input using RxJS operators.
|
||||
|
||||
<code-example header="app/package-search/package-search.component.ts (excerpt)" path="http/src/app/package-search/package-search.component.ts" region="debounce"></code-example>
|
||||
|
||||
The `searchText$` is the sequence of search-box values coming from the user.
|
||||
It's defined as an RxJS `Subject`, which means it is a multicasting `Observable` that can also emit values for itself by calling `next(value)`, as happens in the `search()` method.
|
||||
|
||||
Rather than forward every `searchText` value directly to the injected `PackageSearchService`, the code in `ngOnInit()` pipes search values through three operators, so that a search value reaches the service only if it's a new value and the user stopped typing.
|
||||
|
||||
| RxJS operators | Details |
|
||||
|:--- |:--- |
|
||||
| `debounceTime(500)` | Wait for the user to stop typing, which is 1/2 second in this case. |
|
||||
| `distinctUntilChanged()` | Wait until the search text changes. |
|
||||
| `switchMap()` | Send the search request to the service. |
|
||||
|
||||
The code sets `packages$` to this re-composed `Observable` of search results.
|
||||
The template subscribes to `packages$` with the [AsyncPipe](api/common/AsyncPipe) and displays search results as they arrive.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
See [Using interceptors to request multiple values](guide/http-interceptor-use-cases#cache-refresh) for more about the `withRefresh` option.
|
||||
|
||||
</div>
|
||||
|
||||
## Using the `switchMap()` operator
|
||||
|
||||
The `switchMap()` operator takes a function argument that returns an `Observable`.
|
||||
In the example, `PackageSearchService.search` returns an `Observable`, as other data service methods do.
|
||||
If a previous search request is still in-flight, such as when the network connection is poor, the operator cancels that request and sends a new one.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
**NOTE**: <br />
|
||||
`switchMap()` returns service responses in their original request order, even if the server returns them out of order.
|
||||
|
||||
</div>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
If you think you'll reuse this debouncing logic, consider moving it to a utility function or into the `PackageSearchService` itself.
|
||||
|
||||
</div>
|
||||
|
||||
@reviewed 2023-02-27
|
||||
|
||||
@@ -1,3 +1,49 @@
|
||||
# Pass metadata to interceptors
|
||||
# HTTP - Pass metadata to interceptors
|
||||
|
||||
@reviewed 2022-10-06
|
||||
Many interceptors require or benefit from configuration.
|
||||
Consider an interceptor that retries failed requests.
|
||||
By default, the interceptor might retry a request three times, but you might want to override this retry count for particularly error-prone or sensitive requests.
|
||||
|
||||
`HttpClient` requests contain a *context* that can carry metadata about the request.
|
||||
This context is available for interceptors to read or modify, though it is not transmitted to the backend server when the request is sent.
|
||||
This lets applications or other interceptors tag requests with configuration parameters, such as how many times to retry a request.
|
||||
|
||||
## Create a context token
|
||||
|
||||
Angular stores and retrieves a value in the context using an `HttpContextToken`.
|
||||
You can create a context token using the `new` operator, as in the following example:
|
||||
|
||||
<code-example header="creating a context token" path="http/src/app/http-interceptors/retry-interceptor.ts" region="context-token"></code-example>
|
||||
|
||||
The lambda function `() => 3` passed during the creation of the `HttpContextToken` serves two purposes:
|
||||
|
||||
1. It lets TypeScript infer the type of this token:
|
||||
`HttpContextToken<number>`
|
||||
The request context is type-safe —reading a token from a request's context returns a value of the appropriate type.
|
||||
|
||||
1. It sets the default value for the token.
|
||||
This is the value that the request context returns if no other value was set for this token.
|
||||
Using a default value avoids the need to check if a particular value is set.
|
||||
|
||||
## Set context values when making a request
|
||||
|
||||
When making a request, you can provide an `HttpContext` instance, in which you have already set the context values.
|
||||
|
||||
<code-example header="setting context values" path="http/src/app/http-interceptors/retry-interceptor.ts" region="set-context"></code-example>
|
||||
|
||||
## Read context values in an interceptor
|
||||
|
||||
Within an interceptor, you can read the value of a token in a given request's context with `HttpContext.get()`.
|
||||
If you have not explicitly set a value for the token, Angular returns the default value specified in the token.
|
||||
|
||||
<code-example header="reading context values in an interceptor" path="http/src/app/http-interceptors/retry-interceptor.ts" region="reading-context"></code-example>
|
||||
|
||||
## Contexts are mutable
|
||||
|
||||
Unlike most other aspects of `HttpRequest` instances, the request context is mutable and persists across other immutable transformations of the request.
|
||||
This lets interceptors coordinate operations through the context.
|
||||
For instance, the `RetryInterceptor` example could use a second context token to track how many errors occur during the execution of a given request:
|
||||
|
||||
<code-example header="coordinating operations through the context" path="http/src/app/http-interceptors/retry-interceptor.ts" region="mutable-context"></code-example>
|
||||
|
||||
@reviewed 2022-11-15
|
||||
|
||||
@@ -1,3 +1,221 @@
|
||||
# Request data from a server
|
||||
# HTTP: Request data from a server
|
||||
|
||||
@reviewed 2022-10-06
|
||||
Use the [`HttpClient.get()`](api/common/http/HttpClient#get) method to fetch data from a server.
|
||||
The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received.
|
||||
The return type varies based on the `observe` and `responseType` values that you pass to the call.
|
||||
|
||||
The `get()` method takes two arguments; the endpoint URL from which to fetch, and an *options* object that is used to configure the request.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
options: {
|
||||
headers?: HttpHeaders | {[header: string]: string | string[]},
|
||||
observe?: 'body' | 'events' | 'response',
|
||||
params?: HttpParams|{[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>},
|
||||
reportProgress?: boolean,
|
||||
responseType?: 'arraybuffer'|'blob'|'json'|'text',
|
||||
withCredentials?: boolean,
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
Important options include the *observe* and *responseType* properties.
|
||||
|
||||
* The *observe* option specifies how much of the response to return
|
||||
* The *responseType* option specifies the format in which to return data
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Use the `options` object to configure various other aspects of an outgoing request.
|
||||
In adding headers, for example, the service set the default headers using the `headers` option property.
|
||||
|
||||
Use the `params` property to configure a request with HTTP URL parameters, and the `reportProgress` option to listen for progress events when transferring large amounts of data.
|
||||
|
||||
</div>
|
||||
|
||||
Applications often request JSON data from a server.
|
||||
In the `ConfigService` example, the app needs a configuration file on the server, `config.json`, that specifies resource URLs.
|
||||
|
||||
<code-example header="assets/config.json" path="http/src/assets/config.json"></code-example>
|
||||
|
||||
To fetch this kind of data, the `get()` call needs the following options: `{observe: 'body', responseType: 'json'}`.
|
||||
These are the default values for those options, so the following examples do not pass the options object.
|
||||
Later sections show some of the additional option possibilities.
|
||||
|
||||
<a id="config-service"></a>
|
||||
|
||||
The example conforms to the best practices for creating scalable solutions by defining a re-usable [injectable service](guide/glossary#service "service definition") to perform the data-handling functionality.
|
||||
In addition to fetching data, the service can post-process the data, add error handling, and add retry logic.
|
||||
|
||||
The `ConfigService` fetches this file using the `HttpClient.get()` method.
|
||||
|
||||
<code-example header="app/config/config.service.ts (getConfig v.1)" path="http/src/app/config/config.service.ts" region="getConfig_1"></code-example>
|
||||
|
||||
The `ConfigComponent` injects the `ConfigService` and calls the `getConfig` service method.
|
||||
|
||||
Because the service method returns an `Observable` of configuration data, the component *subscribes* to the method's return value.
|
||||
The subscription callback performs minimal post-processing.
|
||||
It copies the data fields into the component's `config` object, which is data-bound in the component template for display.
|
||||
|
||||
<code-example header="app/config/config.component.ts (showConfig v.1)" path="http/src/app/config/config.component.ts" region="v1"></code-example>
|
||||
|
||||
<a id="always-subscribe"></a>
|
||||
|
||||
## Starting the request
|
||||
|
||||
For all `HttpClient` methods, the method doesn't begin its HTTP request until you call `subscribe()` on the observable the method returns.
|
||||
|
||||
This is true for *all* `HttpClient` *methods*.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
You should always unsubscribe from an observable when a component is destroyed.
|
||||
|
||||
</div>
|
||||
|
||||
All observables returned from `HttpClient` methods are *cold* by design.
|
||||
Execution of the HTTP request is *deferred*, letting you extend the observable with additional operations such as `tap` and `catchError` before anything actually happens.
|
||||
|
||||
Calling `subscribe()` triggers execution of the observable and causes `HttpClient` to compose and send the HTTP request to the server.
|
||||
|
||||
Think of these observables as *blueprints* for actual HTTP requests.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
In fact, each `subscribe()` initiates a separate, independent execution of the observable.
|
||||
Subscribing twice results in two HTTP requests.
|
||||
|
||||
<code-example format="javascript" language="javascript">
|
||||
|
||||
const req = http.get<Heroes>('/api/heroes');
|
||||
// 0 requests made - .subscribe() not called.
|
||||
req.subscribe();
|
||||
// 1 request made.
|
||||
req.subscribe();
|
||||
// 2 requests made.
|
||||
|
||||
</code-example>
|
||||
|
||||
</div>
|
||||
|
||||
<a id="typed-response"></a>
|
||||
|
||||
## Requesting a typed response
|
||||
|
||||
Structure your `HttpClient` request to declare the type of the response object, to make consuming the output easier and more obvious.
|
||||
Specifying the response type acts as a type assertion at compile time.
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
Specifying the response type is a declaration to TypeScript that it should treat your response as being of the given type.
|
||||
This is a build-time check and doesn't guarantee that the server actually responds with an object of this type.
|
||||
It is up to the server to ensure that the type specified by the server API is returned.
|
||||
|
||||
</div>
|
||||
|
||||
To specify the response object type, first define an interface with the required properties.
|
||||
Use an interface rather than a class, because the response is a plain object that cannot be automatically converted to an instance of a class.
|
||||
|
||||
<code-example path="http/src/app/config/config.service.ts" region="config-interface"></code-example>
|
||||
|
||||
Next, specify that interface as the `HttpClient.get()` call's type parameter in the service.
|
||||
|
||||
<code-example header="app/config/config.service.ts (getConfig v.2)" path="http/src/app/config/config.service.ts" region="getConfig_2"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
When you pass an interface as a type parameter to the `HttpClient.get()` method, use the [RxJS `map` operator](guide/rx-library#operators) to transform the response data as needed by the UI.
|
||||
You can then pass the transformed data to the [async pipe](api/common/AsyncPipe).
|
||||
|
||||
</div>
|
||||
|
||||
The callback in the updated component method receives a typed data object, which is easier and safer to consume:
|
||||
|
||||
<code-example header="app/config/config.component.ts (showConfig v.2)" path="http/src/app/config/config.component.ts" region="v2"></code-example>
|
||||
|
||||
To access properties that are defined in an interface, you must explicitly convert the plain object you get from the JSON to the required response type.
|
||||
For example, the following `subscribe` callback receives `data` as an Object, and then type-casts it in order to access the properties.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
.subscribe(data => this.config = {
|
||||
heroesUrl: (data as any).heroesUrl,
|
||||
textfile: (data as any).textfile,
|
||||
});
|
||||
|
||||
</code-example>
|
||||
|
||||
<a id="string-union-types"></a>
|
||||
|
||||
<div class="callout is-important">
|
||||
|
||||
<header><code>observe</code> and <code>response</code> types</header>
|
||||
|
||||
The types of the `observe` and `response` options are *string unions*, rather than plain strings.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
options: {
|
||||
…
|
||||
observe?: 'body' | 'events' | 'response',
|
||||
…
|
||||
responseType?: 'arraybuffer'|'blob'|'json'|'text',
|
||||
…
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
This can cause confusion.
|
||||
For example:
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
// this works
|
||||
client.get('/foo', {responseType: 'text'})
|
||||
|
||||
// but this does NOT work
|
||||
const options = {
|
||||
responseType: 'text',
|
||||
};
|
||||
client.get('/foo', options)
|
||||
|
||||
</code-example>
|
||||
|
||||
In the second case, TypeScript infers the type of `options` to be `{responseType: string}`.
|
||||
The type is too wide to pass to `HttpClient.get` which is expecting the type of `responseType` to be one of the *specific* strings.
|
||||
`HttpClient` is typed explicitly this way so that the compiler can report the correct return type based on the options you provided.
|
||||
|
||||
Use `as const` to let TypeScript know that you really do mean to use a constant string type:
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
const options = {
|
||||
responseType: 'text' as const,
|
||||
};
|
||||
client.get('/foo', options);
|
||||
|
||||
</code-example>
|
||||
|
||||
</div>
|
||||
|
||||
## Reading the full response
|
||||
|
||||
In the previous example, the call to `HttpClient.get()` did not specify any options.
|
||||
By default, it returned the JSON data contained in the response body.
|
||||
|
||||
You might need more information about the transaction than is contained in the response body.
|
||||
Sometimes servers return special headers or status codes to indicate certain conditions that are important to the application workflow.
|
||||
|
||||
Tell `HttpClient` that you want the full response with the `observe` option of the `get()` method:
|
||||
|
||||
<code-example path="http/src/app/config/config.service.ts" region="getConfigResponse"></code-example>
|
||||
|
||||
Now `HttpClient.get()` returns an `Observable` of type `HttpResponse` rather than just the JSON data contained in the body.
|
||||
|
||||
The component's `showConfigResponse()` method displays the response headers as well as the configuration:
|
||||
|
||||
<code-example header="app/config/config.component.ts (showConfigResponse)" path="http/src/app/config/config.component.ts" region="showConfigResponse"></code-example>
|
||||
|
||||
As you can see, the response object has a `body` property of the correct type.
|
||||
|
||||
@reviewed 2023-02-27
|
||||
|
||||
@@ -1,3 +1,35 @@
|
||||
# Security: Cross-site request forgery (XSRF) protection
|
||||
# HTTP client - Security: Cross-Site Request Forgery (XSRF) protection
|
||||
|
||||
@reviewed 2022-10-06
|
||||
[Cross-Site Request Forgery (XSRF or CSRF)](https://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website.
|
||||
|
||||
`HttpClient` supports a [common mechanism](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Cookie-to-header_token) used to prevent XSRF attacks.
|
||||
When performing HTTP requests, an interceptor reads a token from a cookie, by default `XSRF-TOKEN`, and sets it as an HTTP header, `X-XSRF-TOKEN`.
|
||||
Because only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.
|
||||
|
||||
By default, an interceptor sends this header on all mutating requests \(such as POST\)
|
||||
to relative URLs, but not on GET/HEAD requests or on requests with an absolute URL.
|
||||
|
||||
To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called `XSRF-TOKEN` on either the page load or the first GET request.
|
||||
On subsequent requests the server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be sure that only code running on your domain could have sent the request.
|
||||
The token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens.
|
||||
Set the token to a digest of your site's authentication cookie with a salt for added security.
|
||||
|
||||
To prevent collisions in environments where multiple Angular apps share the same domain or subdomain, give each application a unique cookie name.
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
*`HttpClient` supports only the client half of the XSRF protection scheme.*
|
||||
Your backend service must be configured to set the cookie for your page, and to verify that the header is present on all eligible requests.
|
||||
Failing to do so renders Angular's default protection ineffective.
|
||||
|
||||
</div>
|
||||
|
||||
## Configure custom cookie/header names
|
||||
|
||||
If your backend service uses different names for the XSRF token cookie or header, use `HttpClientXsrfModule.withOptions()` to override the defaults.
|
||||
|
||||
<code-example path="http/src/app/app.module.ts" region="xsrf"></code-example>
|
||||
|
||||
<a id="testing-requests"></a>
|
||||
|
||||
@reviewed 2022-11-14
|
||||
|
||||
@@ -1,3 +1,87 @@
|
||||
# Send data to a server
|
||||
# HTTP: Send data to a server
|
||||
|
||||
@reviewed 2022-10-06
|
||||
In addition to fetching data from a server, `HttpClient` supports other HTTP methods such as PUT, POST, and DELETE, which you can use to modify the remote data.
|
||||
|
||||
The sample app for this guide includes an abridged version of the "Tour of Heroes" example that fetches heroes and enables users to add, delete, and update them.
|
||||
The following sections show examples of the data-update methods from the sample's `HeroesService`.
|
||||
|
||||
## Make a POST request
|
||||
|
||||
Apps often send data to a server with a POST request when submitting a form.
|
||||
In the following example, the `HeroesService` makes an HTTP POST request when adding a hero to the database.
|
||||
|
||||
<code-example header="app/heroes/heroes.service.ts (addHero)" path="http/src/app/heroes/heroes.service.ts" region="addHero"></code-example>
|
||||
|
||||
The `HttpClient.post()` method is similar to `get()` in that it has a type parameter, which you can use to specify that you expect the server to return data of a given type.
|
||||
The method takes a resource URL and two additional parameters:
|
||||
|
||||
| Parameter | Details |
|
||||
|:--- |:--- |
|
||||
| body | The data to POST in the body of the request. |
|
||||
| options | An object containing method options which, in this case, specify required headers. |
|
||||
|
||||
The example catches errors as [described above](guide/http-handle-request-errors#error-details).
|
||||
|
||||
The `HeroesComponent` initiates the actual POST operation by subscribing to the `Observable` returned by this service method.
|
||||
|
||||
<code-example header="app/heroes/heroes.component.ts (addHero)" path="http/src/app/heroes/heroes.component.ts" region="add-hero-subscribe"></code-example>
|
||||
|
||||
When the server responds successfully with the newly added hero, the component adds that hero to the displayed `heroes` list.
|
||||
|
||||
## Make a DELETE request
|
||||
|
||||
This application deletes a hero with the `HttpClient.delete` method by passing the hero's ID in the request URL.
|
||||
|
||||
<code-example header="app/heroes/heroes.service.ts (deleteHero)" path="http/src/app/heroes/heroes.service.ts" region="deleteHero"></code-example>
|
||||
|
||||
The `HeroesComponent` initiates the actual DELETE operation by subscribing to the `Observable` returned by this service method.
|
||||
|
||||
<code-example header="app/heroes/heroes.component.ts (deleteHero)" path="http/src/app/heroes/heroes.component.ts" region="delete-hero-subscribe"></code-example>
|
||||
|
||||
The component isn't expecting a result from the delete operation, so it subscribes without a callback.
|
||||
Even though you are not using the result, you still have to subscribe.
|
||||
Calling the `subscribe()` method *executes* the observable, which is what initiates the DELETE request.
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
You must call `subscribe()` or nothing happens.
|
||||
Just calling `HeroesService.deleteHero()` does not initiate the DELETE request.
|
||||
|
||||
</div>
|
||||
|
||||
<code-example path="http/src/app/heroes/heroes.component.ts" region="delete-hero-no-subscribe"></code-example>
|
||||
|
||||
|
||||
## Make a PUT request
|
||||
|
||||
An app can send PUT requests using the HTTP client service.
|
||||
The following `HeroesService` example, like the POST example, replaces a resource with updated data.
|
||||
|
||||
<code-example header="app/heroes/heroes.service.ts (updateHero)" path="http/src/app/heroes/heroes.service.ts" region="updateHero"></code-example>
|
||||
|
||||
As for any of the HTTP methods that return an observable, the caller, `HeroesComponent.update()` [must `subscribe()`](guide/http-request-data-from-server#always-subscribe "Why you must always subscribe.") to the observable returned from the `HttpClient.put()` in order to initiate the request.
|
||||
|
||||
## Add and updating headers
|
||||
|
||||
Many servers require extra headers for save operations.
|
||||
For example, a server might require an authorization token, or "Content-Type" header to explicitly declare the MIME type of the request body.
|
||||
|
||||
### Add headers
|
||||
|
||||
The `HeroesService` defines such headers in an `httpOptions` object that are passed to every `HttpClient` save method.
|
||||
|
||||
<code-example header="app/heroes/heroes.service.ts (httpOptions)" path="http/src/app/heroes/heroes.service.ts" region="http-options"></code-example>
|
||||
|
||||
### Update headers
|
||||
|
||||
You can't directly modify the existing headers within the previous options
|
||||
object because instances of the `HttpHeaders` class are immutable.
|
||||
Use the `set()` method instead, to return a clone of the current instance with the new changes applied.
|
||||
|
||||
The following example shows how, when an old token expires, you can update the authorization header before making the next request.
|
||||
|
||||
<code-example linenums="false" path="http/src/app/heroes/heroes.service.ts" region="update-headers"></code-example>
|
||||
|
||||
<a id="url-params"></a>
|
||||
|
||||
@reviewed 2023-03-16
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
# HTTP Server communication
|
||||
|
||||
Most front-end applications need to communicate with a server over the HTTP protocol, to download or upload data and access other back-end services.
|
||||
|
||||
## Setup for server communication
|
||||
|
||||
Before you can use `HttpClient`, you need to import the Angular `HttpClientModule`.
|
||||
Most apps do so in the root `AppModule`.
|
||||
|
||||
<code-example header="app/app.module.ts (excerpt)" path="http/src/app/app.module.ts" region="sketch"></code-example>
|
||||
|
||||
You can then inject the `HttpClient` service as a dependency of an application class, as shown in the following `ConfigService` example.
|
||||
|
||||
<code-example header="app/config/config.service.ts (excerpt)" path="http/src/app/config/config.service.ts" region="proto"></code-example>
|
||||
|
||||
The `HttpClient` service makes use of [observables](guide/glossary#observable "Observable definition") for all transactions.
|
||||
You must import the RxJS observable and operator symbols that appear in the example snippets.
|
||||
These `ConfigService` imports are typical.
|
||||
|
||||
<code-example header="app/config/config.service.ts (RxJS imports)" path="http/src/app/config/config.service.ts" region="rxjs-imports"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
You can run the <live-example></live-example> that accompanies this guide.
|
||||
|
||||
The sample app does not require a data server.
|
||||
It relies on the [Angular *in-memory-web-api*](https://github.com/angular/angular/tree/main/packages/misc/angular-in-memory-web-api), which replaces the *HttpClient* module's `HttpBackend`.
|
||||
The replacement service simulates the behavior of a REST-like backend.
|
||||
|
||||
Look at the `AppModule` *imports* to see how it is configured.
|
||||
|
||||
</div>
|
||||
|
||||
## Requesting data from a server
|
||||
|
||||
Use the [`HttpClient.get()`](api/common/http/HttpClient#get) method to fetch data from a server.
|
||||
The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received.
|
||||
The return type varies based on the `observe` and `responseType` values that you pass to the call.
|
||||
|
||||
The `get()` method takes two arguments; the endpoint URL from which to fetch, and an *options* object that is used to configure the request.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
options: {
|
||||
headers?: HttpHeaders | {[header: string]: string | string[]},
|
||||
observe?: 'body' | 'events' | 'response',
|
||||
params?: HttpParams|{[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>},
|
||||
reportProgress?: boolean,
|
||||
responseType?: 'arraybuffer'|'blob'|'json'|'text',
|
||||
withCredentials?: boolean,
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
Important options include the *observe* and *responseType* properties.
|
||||
|
||||
* The *observe* option specifies how much of the response to return
|
||||
* The *responseType* option specifies the format in which to return data
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Use the `options` object to configure various other aspects of an outgoing request.
|
||||
In adding headers, for example, the service set the default headers using the `headers` option property.
|
||||
|
||||
Use the `params` property to configure a request with [TTP URL parameters, and the `reportProgress` option to listen for progress events when transferring large amounts of data.
|
||||
|
||||
</div>
|
||||
|
||||
Applications often request JSON data from a server.
|
||||
In the `ConfigService` example, the app needs a configuration file on the server, `config.json`, that specifies resource URLs.
|
||||
|
||||
<code-example header="assets/config.json" path="http/src/assets/config.json"></code-example>
|
||||
|
||||
To fetch this kind of data, the `get()` call needs the following options: `{observe: 'body', responseType: 'json'}`.
|
||||
These are the default values for those options, so the following examples do not pass the options object.
|
||||
Later sections show some of the additional option possibilities.
|
||||
|
||||
<a id="config-service"></a>
|
||||
|
||||
The example conforms to the best practices for creating scalable solutions by defining a re-usable [injectable service](guide/glossary#service "service definition") to perform the data-handling functionality.
|
||||
In addition to fetching data, the service can post-process the data, add error handling, and add retry logic.
|
||||
|
||||
The `ConfigService` fetches this file using the `HttpClient.get()` method.
|
||||
|
||||
<code-example header="app/config/config.service.ts (getConfig v.1)" path="http/src/app/config/config.service.ts" region="getConfig_1"></code-example>
|
||||
|
||||
The `ConfigComponent` injects the `ConfigService` and calls the `getConfig` service method.
|
||||
|
||||
Because the service method returns an `Observable` of configuration data, the component *subscribes* to the method's return value.
|
||||
The subscription callback performs minimal post-processing.
|
||||
It copies the data fields into the component's `config` object, which is data-bound in the component template for display.
|
||||
|
||||
<code-example header="app/config/config.component.ts (showConfig v.1)" path="http/src/app/config/config.component.ts" region="v1"></code-example>
|
||||
|
||||
<a id="always-subscribe"></a>
|
||||
|
||||
### Starting the request
|
||||
|
||||
For all `HttpClient` methods, the method doesn't begin its HTTP request until you call `subscribe()` on the observable the method returns.
|
||||
|
||||
This is true for *all* `HttpClient` *methods*.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
You should always unsubscribe from an observable when a component is destroyed.
|
||||
|
||||
</div>
|
||||
|
||||
All observables returned from `HttpClient` methods are *cold* by design.
|
||||
Execution of the HTTP request is *deferred*, letting you extend the observable with additional operations such as `tap` and `catchError` before anything actually happens.
|
||||
|
||||
Calling `subscribe()` triggers execution of the observable and causes `HttpClient` to compose and send the HTTP request to the server.
|
||||
|
||||
Think of these observables as *blueprints* for actual HTTP requests.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
In fact, each `subscribe()` initiates a separate, independent execution of the observable.
|
||||
Subscribing twice results in two HTTP requests.
|
||||
|
||||
<code-example format="javascript" language="javascript">
|
||||
|
||||
const req = http.get<Heroes>('/api/heroes');
|
||||
// 0 requests made - .subscribe() not called.
|
||||
req.subscribe();
|
||||
// 1 request made.
|
||||
req.subscribe();
|
||||
// 2 requests made.
|
||||
|
||||
</code-example>
|
||||
|
||||
</div>
|
||||
|
||||
<a id="typed-response"></a>
|
||||
|
||||
### Requesting a typed response
|
||||
|
||||
Structure your `HttpClient` request to declare the type of the response object, to make consuming the output easier and more obvious.
|
||||
Specifying the response type acts as a type assertion at compile time.
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
Specifying the response type is a declaration to TypeScript that it should treat your response as being of the given type.
|
||||
This is a build-time check and doesn't guarantee that the server actually responds with an object of this type.
|
||||
It is up to the server to ensure that the type specified by the server API is returned.
|
||||
|
||||
</div>
|
||||
|
||||
To specify the response object type, first define an interface with the required properties.
|
||||
Use an interface rather than a class, because the response is a plain object that cannot be automatically converted to an instance of a class.
|
||||
|
||||
<code-example path="http/src/app/config/config.service.ts" region="config-interface"></code-example>
|
||||
|
||||
Next, specify that interface as the `HttpClient.get()` call's type parameter in the service.
|
||||
|
||||
<code-example header="app/config/config.service.ts (getConfig v.2)" path="http/src/app/config/config.service.ts" region="getConfig_2"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
When you pass an interface as a type parameter to the `HttpClient.get()` method, use the [RxJS `map` operator](guide/rx-library#operators) to transform the response data as needed by the UI.
|
||||
You can then pass the transformed data to the [async pipe](api/common/AsyncPipe).
|
||||
|
||||
</div>
|
||||
|
||||
The callback in the updated component method receives a typed data object, which is easier and safer to consume:
|
||||
|
||||
<code-example header="app/config/config.component.ts (showConfig v.2)" path="http/src/app/config/config.component.ts" region="v2"></code-example>
|
||||
|
||||
To access properties that are defined in an interface, you must explicitly convert the plain object you get from the JSON to the required response type.
|
||||
For example, the following `subscribe` callback receives `data` as an Object, and then type-casts it in order to access the properties.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
.subscribe(data => this.config = {
|
||||
heroesUrl: (data as any).heroesUrl,
|
||||
textfile: (data as any).textfile,
|
||||
});
|
||||
|
||||
</code-example>
|
||||
|
||||
<a id="string-union-types"></a>
|
||||
|
||||
<div class="callout is-important">
|
||||
|
||||
<header><code>observe</code> and <code>response</code> types</header>
|
||||
|
||||
The types of the `observe` and `response` options are *string unions*, rather than plain strings.
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
options: {
|
||||
…
|
||||
observe?: 'body' | 'events' | 'response',
|
||||
…
|
||||
responseType?: 'arraybuffer'|'blob'|'json'|'text',
|
||||
…
|
||||
}
|
||||
|
||||
</code-example>
|
||||
|
||||
This can cause confusion.
|
||||
For example:
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
// this works
|
||||
client.get('/foo', {responseType: 'text'})
|
||||
|
||||
// but this does NOT work
|
||||
const options = {
|
||||
responseType: 'text',
|
||||
};
|
||||
client.get('/foo', options)
|
||||
|
||||
</code-example>
|
||||
|
||||
In the second case, TypeScript infers the type of `options` to be `{responseType: string}`.
|
||||
The type is too wide to pass to `HttpClient.get` which is expecting the type of `responseType` to be one of the *specific* strings.
|
||||
`HttpClient` is typed explicitly this way so that the compiler can report the correct return type based on the options you provided.
|
||||
|
||||
Use `as const` to let TypeScript know that you really do mean to use a constant string type:
|
||||
|
||||
<code-example format="typescript" language="typescript">
|
||||
|
||||
const options = {
|
||||
responseType: 'text' as const,
|
||||
};
|
||||
client.get('/foo', options);
|
||||
|
||||
</code-example>
|
||||
|
||||
</div>
|
||||
|
||||
### Reading the full response
|
||||
|
||||
In the previous example, the call to `HttpClient.get()` did not specify any options.
|
||||
By default, it returned the JSON data contained in the response body.
|
||||
|
||||
You might need more information about the transaction than is contained in the response body.
|
||||
Sometimes servers return special headers or status codes to indicate certain conditions that are important to the application workflow.
|
||||
|
||||
Tell `HttpClient` that you want the full response with the `observe` option of the `get()` method:
|
||||
|
||||
<code-example path="http/src/app/config/config.service.ts" region="getConfigResponse"></code-example>
|
||||
|
||||
Now `HttpClient.get()` returns an `Observable` of type `HttpResponse` rather than just the JSON data contained in the body.
|
||||
|
||||
The component's `showConfigResponse()` method displays the response headers as well as the configuration:
|
||||
|
||||
<code-example header="app/config/config.component.ts (showConfigResponse)" path="http/src/app/config/config.component.ts" region="showConfigResponse"></code-example>
|
||||
|
||||
As you can see, the response object has a `body` property of the correct type.
|
||||
|
||||
@reviewed 2023-02-27
|
||||
@@ -1,3 +1,30 @@
|
||||
# Setup for server communication
|
||||
# HTTP: Setup for server communication
|
||||
|
||||
@reviewed 2022-10-06
|
||||
Before you can use `HttpClient`, you need to import the Angular `HttpClientModule`.
|
||||
Most apps do so in the root `AppModule`.
|
||||
|
||||
<code-example header="app/app.module.ts (excerpt)" path="http/src/app/app.module.ts" region="sketch"></code-example>
|
||||
|
||||
You can then inject the `HttpClient` service as a dependency of an application class, as shown in the following `ConfigService` example.
|
||||
|
||||
<code-example header="app/config/config.service.ts (excerpt)" path="http/src/app/config/config.service.ts" region="proto"></code-example>
|
||||
|
||||
The `HttpClient` service makes use of [observables](guide/glossary#observable "Observable definition") for all transactions.
|
||||
You must import the RxJS observable and operator symbols that appear in the example snippets.
|
||||
These `ConfigService` imports are typical.
|
||||
|
||||
<code-example header="app/config/config.service.ts (RxJS imports)" path="http/src/app/config/config.service.ts" region="rxjs-imports"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
You can run the <live-example></live-example> that accompanies this guide.
|
||||
|
||||
The sample app does not require a data server.
|
||||
It relies on the [Angular *in-memory-web-api*](https://github.com/angular/angular/tree/main/packages/misc/angular-in-memory-web-api), which replaces the *HttpClient* module's `HttpBackend`.
|
||||
The replacement service simulates the behavior of a REST-like backend.
|
||||
|
||||
Look at the `AppModule` *imports* to see how it is configured.
|
||||
|
||||
</div>
|
||||
|
||||
@reviewed 2022-11-03
|
||||
|
||||
@@ -1,3 +1,75 @@
|
||||
# Test HTTP requests
|
||||
# HTTP client - Test requests
|
||||
|
||||
@reviewed 2022-10-06
|
||||
As for any external dependency, you must mock the HTTP backend so your tests can simulate interaction with a remote server.
|
||||
The `@angular/common/http/testing` library makes it straightforward to set up such mocking.
|
||||
|
||||
## HTTP testing library
|
||||
|
||||
Angular's HTTP testing library is designed for a pattern of testing in which the app executes code and makes requests first.
|
||||
The test then expects that certain requests have or have not been made, performs assertions against those requests, and finally provides responses by "flushing" each expected request.
|
||||
|
||||
At the end, tests can verify that the app made no unexpected requests.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
You can run <live-example stackblitz="specs">these sample tests</live-example> in a live coding environment.
|
||||
|
||||
The tests described in this guide are in `src/testing/http-client.spec.ts`.
|
||||
There are also tests of an application data service that call `HttpClient` in `src/app/heroes/heroes.service.spec.ts`.
|
||||
|
||||
</div>
|
||||
|
||||
## Setup for testing
|
||||
|
||||
To begin testing calls to `HttpClient`, import the `HttpClientTestingModule` and the mocking controller, `HttpTestingController`, along with the other symbols your tests require.
|
||||
|
||||
<code-example header="app/testing/http-client.spec.ts (imports)" path="http/src/testing/http-client.spec.ts" region="imports"></code-example>
|
||||
|
||||
Then add the `HttpClientTestingModule` to the `TestBed` and continue with the setup of the *service-under-test*.
|
||||
|
||||
<code-example header="app/testing/http-client.spec.ts(setup)" path="http/src/testing/http-client.spec.ts" region="setup"></code-example>
|
||||
|
||||
Now requests made in the course of your tests hit the testing backend instead of the normal backend.
|
||||
|
||||
This setup also calls `TestBed.inject()` to inject the `HttpClient` service and the mocking controller so they can be referenced during the tests.
|
||||
|
||||
## Expect and answer requests
|
||||
|
||||
Now you can write a test that expects a GET Request to occur and provides a mock response.
|
||||
|
||||
<code-example header="app/testing/http-client.spec.ts (HttpClient.get)" path="http/src/testing/http-client.spec.ts" region="get-test"></code-example>
|
||||
|
||||
The last step, verifying that no requests remain outstanding, is common enough for you to move it into an `afterEach()` step:
|
||||
|
||||
<code-example path="http/src/testing/http-client.spec.ts" region="afterEach"></code-example>
|
||||
|
||||
### Custom request expectations
|
||||
|
||||
If matching by URL isn't sufficient, it's possible to implement your own matching function.
|
||||
For example, you could look for an outgoing request that has an authorization header:
|
||||
|
||||
<code-example path="http/src/testing/http-client.spec.ts" region="predicate"></code-example>
|
||||
|
||||
As with the previous `expectOne()`, the test fails if 0 or 2+ requests satisfy this predicate.
|
||||
|
||||
### Handle more than one request
|
||||
|
||||
If you need to respond to duplicate requests in your test, use the `match()` API instead of `expectOne()`.
|
||||
It takes the same arguments but returns an array of matching requests.
|
||||
Once returned, these requests are removed from future matching and you are responsible for flushing and verifying them.
|
||||
|
||||
<code-example path="http/src/testing/http-client.spec.ts" region="multi-request"></code-example>
|
||||
|
||||
## Test for errors
|
||||
|
||||
You should test the app's defenses against HTTP requests that fail.
|
||||
|
||||
Call `request.flush()` with an error message, as seen in the following example.
|
||||
|
||||
<code-example path="http/src/testing/http-client.spec.ts" region="404"></code-example>
|
||||
|
||||
Alternatively, call `request.error()` with a `ProgressEvent`.
|
||||
|
||||
<code-example path="http/src/testing/http-client.spec.ts" region="network-error"></code-example>
|
||||
|
||||
@reviewed 2022-11-14
|
||||
|
||||
@@ -1,3 +1,37 @@
|
||||
# Track and show request progress
|
||||
# HTTP - Track and show request progress
|
||||
|
||||
@reviewed 2022-10-06
|
||||
Sometimes applications transfer large amounts of data and those transfers can take a long time. File uploads are a typical example. You can give the users a better experience by providing feedback on the progress of such transfers.
|
||||
|
||||
## Make a request
|
||||
|
||||
To make a request with progress events enabled, create an instance of `HttpRequest` with the `reportProgress` option set true to enable tracking of progress events.
|
||||
|
||||
<code-example header="app/uploader/uploader.service.ts (upload request)" path="http/src/app/uploader/uploader.service.ts" region="upload-request"></code-example>
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
**TIP**: <br />
|
||||
Every progress event triggers change detection, so only turn them on if you need to report progress in the UI.
|
||||
|
||||
When using `HttpClient.request()` with an HTTP method, configure the method with `observe: 'events'` to see all events, including the progress of transfers.
|
||||
|
||||
</div>
|
||||
|
||||
## Track request progress
|
||||
|
||||
Next, pass this request object to the `HttpClient.request()` method, which returns an `Observable` of `HttpEvents` \(the same events processed by [interceptors](guide/http-intercept-requests-and-responses#interceptor-events)\).
|
||||
|
||||
<code-example header="app/uploader/uploader.service.ts (upload body)" path="http/src/app/uploader/uploader.service.ts" region="upload-body"></code-example>
|
||||
|
||||
The `getEventMessage` method interprets each type of `HttpEvent` in the event stream.
|
||||
|
||||
<code-example header="app/uploader/uploader.service.ts (getEventMessage)" path="http/src/app/uploader/uploader.service.ts" region="getEventMessage"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The sample app for this guide doesn't have a server that accepts uploaded files.
|
||||
The `UploadInterceptor` in `app/http-interceptors/upload-interceptor.ts` intercepts and short-circuits upload requests by returning an observable of simulated events.
|
||||
|
||||
</div>
|
||||
|
||||
@reviewed 2023-02-27
|
||||
|
||||
@@ -2,22 +2,31 @@
|
||||
|
||||
To take advantage of the localization features of Angular, use the [Angular CLI][AioCliMain] to add the `@angular/localize` package to your project.
|
||||
|
||||
To add the `@angular/localize` package, use the following command to update the `package.json` and `polyfills.ts` files in your project.
|
||||
To add the `@angular/localize` package, use the following command to update the `package.json` and TypeScript configuration files in your project.
|
||||
|
||||
<code-example path="i18n/doc-files/commands.sh" region="add-localize"></code-example>
|
||||
|
||||
It adds `types: ["@angular/localize"]` in the TypeScript configuration files as well as the reference to the type definition of `@angular/localize` at the top of the `main.ts` file.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
For more information about `package.json` and `polyfill.ts` files, see [Workspace npm dependencies][AioGuideNpmPackages].
|
||||
For more information about `package.json` and `tsconfig.json` files, see [Workspace npm dependencies][AioGuideNpmPackages] and [TypeScript Configuration][AioGuideTsConfig].
|
||||
|
||||
</div>
|
||||
|
||||
If `@angular/localize` is not installed and you try to build a localized version of your project, the [Angular CLI][AioCliMain] generates an error.
|
||||
If `@angular/localize` is not installed and you try to build a localized version of your project (for example, while using the `i18n` attributes in templates), the [Angular CLI][AioCliMain] will generate an error, which would contain the steps that you can take to enable i18n for your project.
|
||||
|
||||
<!--todo: add example error -->
|
||||
## Options
|
||||
|
||||
| OPTION | DESCRIPTION | VALUE TYPE | DEFAULT VALUE
|
||||
|:--- |:--- |:------ |:------
|
||||
| `--project` | The name of the project. | `string` |
|
||||
| `--use-at-runtime` | If set, then `$localize` can be used at runtime. Also `@angular/localize` gets included in the `dependencies` section of `package.json`, rather than `devDependencies`, which is the default. | `boolean` | `false`
|
||||
|
||||
For more available options, see [ng add][AioCliAdd] in [Angular CLI][AioCliMain].
|
||||
## What's next
|
||||
|
||||
* [@angular/localize API][AioApiLocalize]
|
||||
* [Refer to locales by ID][AioGuideI18nCommonLocaleId]
|
||||
|
||||
<!-- links -->
|
||||
@@ -28,8 +37,14 @@ If `@angular/localize` is not installed and you try to build a localized version
|
||||
|
||||
[AioGuideNpmPackages]: guide/npm-packages "Workspace npm dependencies | Angular"
|
||||
|
||||
[AioGuideTsConfig]: guide/typescript-configuration "TypeScript Configuration | Angular"
|
||||
|
||||
[AioCliAdd]: cli/add "ng add | CLI | Angular"
|
||||
|
||||
[AioApiLocalize]: api/localize "$localize | @angular/localize - API | Angular"
|
||||
|
||||
<!-- external links -->
|
||||
|
||||
<!-- end links -->
|
||||
|
||||
@reviewed 2021-10-07
|
||||
@reviewed 2023-03-10
|
||||
|
||||
@@ -92,7 +92,7 @@ To create a translation file for a locale or language, complete the following ac
|
||||
|
||||
<code-example language="file">
|
||||
|
||||
messages.xlf --> message.{locale}.xlf
|
||||
messages.xlf --> messages.{locale}.xlf
|
||||
|
||||
</code-example>
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ If you choose this option, make sure to turn off the `guessRoutes` option.
|
||||
|
||||
<code-example format="shell" language="shell">
|
||||
|
||||
ng run <app-name>:prerender --no-guess-routes --routes /product/1 /product/1
|
||||
ng run <app-name>:prerender --no-guess-routes --routes /product/1 /product/2
|
||||
|
||||
</code-example>
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ In the `ItemListComponent` the `@Input()`, `items`, has a type of `Item[]`.
|
||||
|
||||
<code-example header="src/app/item-list.component.ts" path="property-binding/src/app/item-list/item-list.component.ts" region="item-input"></code-example>
|
||||
|
||||
Notice that `Item` is an object that it has two properties, an `id` and a `name`.
|
||||
Notice that `Item` is an object and it has two properties, an `id` and a `name`.
|
||||
|
||||
<code-example header="src/app/item.ts" path="property-binding/src/app/item.ts" region="item-class"></code-example>
|
||||
|
||||
|
||||
@@ -257,7 +257,7 @@ Because a wildcard route is the least specific route, place it last in the route
|
||||
|
||||
</div>
|
||||
|
||||
To test this feature, add a button with a `RouterLink` to the `HeroListComponent` template and set the link to a non-existant route called `"/sidekicks"`.
|
||||
To test this feature, add a button with a `RouterLink` to the `HeroListComponent` template and set the link to a non-existent route called `"/sidekicks"`.
|
||||
|
||||
<code-example header="src/app/hero-list/hero-list.component.html (excerpt)" path="router/src/app/hero-list/hero-list.component.1.html"></code-example>
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ To get information from a route:
|
||||
* [`ActivatedRoute`](api/router/ActivatedRoute)
|
||||
* [`ParamMap`](api/router/ParamMap)
|
||||
|
||||
1. Inject an instance of `ActivatedRoute` by adding it to your application's constructor:
|
||||
1. Inject an instance of `ActivatedRoute` by adding it to your component's constructor:
|
||||
|
||||
<code-example header="In the component class (excerpt)" path="router/src/app/heroes/hero-detail/hero-detail.component.ts" region="activated-route"></code-example>
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ To install Angular on your local system, you need the following:
|
||||
|
||||
## Install the Angular CLI
|
||||
|
||||
You use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
|
||||
You can use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
|
||||
|
||||
To install the Angular CLI, open a terminal window and run the following command:
|
||||
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
# Migrate an existing Angular project to standalone
|
||||
|
||||
As of version 15.2.0, Angular offers a [schematic](guide/schematics) to help project authors convert existing projects to [the new standalone APIs](guide/standalone-components). The schematic aims to transform as much code as possible automatically, but it may require some manual fixes by the project author. Run the schematic with the following command:
|
||||
|
||||
<code-example format="shell" language="shell">
|
||||
|
||||
ng generate @angular/core:standalone
|
||||
|
||||
</code-example>
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using the schematic, please ensure that the project:
|
||||
1. Is using Angular 15.2.0 or later.
|
||||
2. Builds without any compilation errors.
|
||||
3. Is on a clean Git branch and all work is saved.
|
||||
|
||||
## Schematic options
|
||||
|
||||
| Option | Details |
|
||||
|:--- |:--- |
|
||||
| `mode` | The transformation to perform. See [Migration modes](#migration-modes) below for details on the available options. |
|
||||
| `path` | The path to migrate, relative to the project root. You can use this option to migrate sections of your project incrementally. |
|
||||
|
||||
## Migrations steps
|
||||
|
||||
The migration process is composed of three steps. You'll have to run it multiple times and check manually that the project builds and behaves as expected.
|
||||
|
||||
<div class="callout is-helpful">
|
||||
|
||||
<header>Note</header>
|
||||
|
||||
While the schematic can automatically update most code, some edge cases require developer intervention.
|
||||
You should plan to apply manual fixes after each step of the migration. Additionally, the new code generated by the schematic may not match your code's formatting rules.
|
||||
|
||||
</div>
|
||||
|
||||
Run the migration in the order listed below, verifying that your code builds and runs between each step:
|
||||
1. Run `ng g @angular/core:standalone` and select "Convert all components, directives and pipes to standalone"
|
||||
2. Run `ng g @angular/core:standalone` and select "Remove unnecessary NgModule classes"
|
||||
3. Run `ng g @angular/core:standalone` and select "Bootstrap the project using standalone APIs"
|
||||
4. Run any linting and formatting checks, fix any failures, and commit the result
|
||||
|
||||
## After the migration
|
||||
|
||||
Congratulations, your application has been converted to standalone 🎉. These are some optional follow-up steps you may want to take now:
|
||||
* Find and remove any remaining `NgModule` declarations: since the ["Remove unnecessary NgModules" step](#remove-unnecessary-ngmodules) cannot remove all modules automatically, you may have to remove the remaining declarations manually.
|
||||
* Run the project's unit tests and fix any failures.
|
||||
* Run any code formatters, if the project uses automatic formatting.
|
||||
* Run any linters in your project and fix new warnings. Some linters support a `--fix` flag that may resolve so warnings automatically.
|
||||
|
||||
## Migration modes
|
||||
The migration has the following modes:
|
||||
1. Convert declarations to standalone.
|
||||
2. Remove unnecessary NgModules.
|
||||
3. Switch to standalone bootstrapping API.
|
||||
You should run these migrations in the order given.
|
||||
|
||||
### Convert declarations to standalone
|
||||
|
||||
In this mode, the migration converts all components, directives and pipes to standalone by setting `standalone: true` and adding dependencies to their `imports` array.
|
||||
|
||||
<div class="callout is-helpful">
|
||||
|
||||
The schematic ignores NgModules which bootstrap a component during this step because they are likely root modules used by `bootstrapModule` rather than the standalone-compatible `bootstrapApplication`. The schematic converts these declarations automatically as a part of the ["Switch to standalone bootstrapping API"](#switch-to-standalone-bootstrapping-api) step.
|
||||
|
||||
</div>
|
||||
|
||||
**Before:**
|
||||
```typescript
|
||||
// shared.module.ts
|
||||
@NgModule({
|
||||
imports: [CommonModule],
|
||||
declarations: [GreeterComponent],
|
||||
exports: [GreeterComponent]
|
||||
})
|
||||
export class SharedModule {}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// greeter.component.ts
|
||||
@Component({
|
||||
selector: 'greeter',
|
||||
template: '<div *ngIf="showGreeting">Hello</div>',
|
||||
})
|
||||
export class GreeterComponent {
|
||||
showGreeting = true;
|
||||
}
|
||||
```
|
||||
|
||||
**After:**
|
||||
```typescript
|
||||
// shared.module.ts
|
||||
@NgModule({
|
||||
imports: [CommonModule, GreeterComponent],
|
||||
exports: [GreeterComponent]
|
||||
})
|
||||
export class SharedModule {}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// greeter.component.ts
|
||||
@Component({
|
||||
selector: 'greeter',
|
||||
template: '<div *ngIf="showGreeting">Hello</div>',
|
||||
standalone: true,
|
||||
imports: [NgIf]
|
||||
})
|
||||
export class GreeterComponent {
|
||||
showGreeting = true;
|
||||
}
|
||||
```
|
||||
|
||||
### Remove unnecessary NgModules
|
||||
After converting all declarations to standalone, many NgModules can be safely removed. This step deletes such module declarations and as many corresponding references as possible. If the migration cannot delete a reference automatically, it leaves the following TODO comment so that you can delete the NgModule manually:
|
||||
```typescript
|
||||
/* TODO(standalone-migration): clean up removed NgModule reference manually */
|
||||
```
|
||||
|
||||
The migration considers a module safe to remove if that module:
|
||||
* Has no `declarations`.
|
||||
* Has no `providers`.
|
||||
* Has no `bootstrap` components.
|
||||
* Has no `imports` that reference a `ModuleWithProviders` symbol or a module that can't be removed.
|
||||
* Has no class members. Empty constructors are ignored.
|
||||
|
||||
**Before:**
|
||||
```typescript
|
||||
// importer.module.ts
|
||||
@NgModule({
|
||||
imports: [FooComponent, BarPipe],
|
||||
exports: [FooComponent, BarPipe]
|
||||
})
|
||||
export class ImporterModule {}
|
||||
```
|
||||
|
||||
**After:**
|
||||
```typescript
|
||||
// importer.module.ts
|
||||
// Does not exist!
|
||||
```
|
||||
|
||||
### Switch to standalone bootstrapping API
|
||||
This step converts any usages of `bootstrapModule` to the new, standalone-based `bootstrapApplication`. It also switches the root component to `standalone: true` and deletes the root NgModule. If the root module has any `providers` or `imports`, the migration attempts to copy as much of this configuration as possible into the new bootstrap call.
|
||||
|
||||
**Before:**
|
||||
```typescript
|
||||
// ./app/app.module.ts
|
||||
import { NgModule } from '@angular/core';
|
||||
import { AppComponent } from './app.component';
|
||||
|
||||
@NgModule({
|
||||
declarations: [AppComponent],
|
||||
bootstrap: [AppComponent]
|
||||
})
|
||||
export class AppModule {}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ./app/app.component.ts
|
||||
@Component({ selector: 'app', template: 'hello' })
|
||||
export class AppComponent {}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ./main.ts
|
||||
import { platformBrowser } from '@angular/platform-browser';
|
||||
import { AppModule } from './app/app.module';
|
||||
|
||||
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
|
||||
```
|
||||
|
||||
**After:**
|
||||
```typescript
|
||||
// ./app/app.module.ts
|
||||
// Does not exist!
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ./app/app.component.ts
|
||||
@Component({ selector: 'app', template: 'hello', standalone: true })
|
||||
export class AppComponent {}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ./main.ts
|
||||
import { bootstrapApplication } from '@angular/platform-browser';
|
||||
import { AppComponent } from './app/app.component';
|
||||
|
||||
bootstrapApplication(AppComponent).catch(e => console.error(e));
|
||||
```
|
||||
|
||||
## Common problems
|
||||
Some common problems that may prevent the schematic from working correctly include:
|
||||
* Compilation errors - if the project has compilation errors, Angular cannot analyze and migrate it correctly.
|
||||
* Files not included in a tsconfig - the schematic determines which files to migrate by analyzing your project's `tsconfig.json` files. The schematic excludes any files not captured by a tsconfig.
|
||||
* Code that cannot be statically analyzed - the schematic uses static analysis to understand your code and determine where to make changes. The migration may skip any classes with metadata that cannot be statically analyzed at build time.
|
||||
|
||||
## Limitations
|
||||
Due to the size and complexity of the migration, there are some cases that the schematic cannot handle:
|
||||
* Because unit tests are not ahead-of-time (AoT) compiled, `imports` added to components in unit tests might not be entirely correct.
|
||||
* The schematic relies on direct calls to Angular APIs. The schematic cannot recognize custom wrappers around Angular APIs. For example, if there you define a custom `customConfigureTestModule` function that wraps `TestBed.configureTestingModule`, components it declares may not be recognized.
|
||||
|
||||
@reviewed 2023-02-15
|
||||
@@ -20,7 +20,7 @@ For the example application that this page describes, see the <live-example name
|
||||
When structural directives are applied they generally are prefixed by an asterisk, `*`, such as `*ngIf`. This convention is shorthand that Angular interprets and converts into a longer form.
|
||||
Angular transforms the asterisk in front of a structural directive into an `<ng-template>` that surrounds the host element and its descendants.
|
||||
|
||||
For example, let's take the following code which uses an `*ngIf` to displays the hero's name if `hero` exists:
|
||||
For example, let's take the following code which uses an `*ngIf` to display the hero's name if `hero` exists:
|
||||
|
||||
<code-example path="structural-directives/src/app/app.component.html" header="src/app/app.component.html (asterisk)" region="asterisk"></code-example>
|
||||
|
||||
@@ -59,7 +59,7 @@ named `$implicit`.
|
||||
|
||||
Angular sets `let-hero` to the value of the context's `$implicit` property, which `NgFor` has initialized with the hero for the current iteration.
|
||||
|
||||
For more information, see the [NgFor API](api/common/NgForOf "API: NgFor") and [NgForOf API](api/common/NgForOf) documentation.
|
||||
For more information, see the [NgFor API](api/common/NgFor "API: NgFor") and [NgForOf API](api/common/NgForOf) documentation.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
|
||||
@@ -812,22 +812,13 @@ Testing the `DashboardComponent` seemed daunting in part because it involves the
|
||||
|
||||
<code-example header="app/dashboard/dashboard.component.ts (constructor)" path="testing/src/app/dashboard/dashboard.component.ts" region="ctor"></code-example>
|
||||
|
||||
Mocking the `HeroService` with a spy is a [familiar story](#component-with-async-service).
|
||||
But the `Router` has a complicated API and is entwined with other services and application preconditions.
|
||||
Might it be difficult to mock?
|
||||
|
||||
Fortunately, not in this case because the `DashboardComponent` isn't doing much with the `Router`
|
||||
|
||||
<code-example header="app/dashboard/dashboard.component.ts (goToDetail)" path="testing/src/app/dashboard/dashboard.component.ts" region="goto-detail" ></code-example>
|
||||
|
||||
This is often the case with *routing components*.
|
||||
As a rule you test the component, not the router, and care only if the component navigates with the right address under the given conditions.
|
||||
Angular provides test helpers to reduce boilerplate and more effectively test code which depends on the Router and HttpClient.
|
||||
|
||||
Providing a router spy for *this component* test suite happens to be as easy as providing a `HeroService` spy.
|
||||
<code-example header="app/dashboard/dashboard.component.spec.ts" path="testing/src/app/dashboard/dashboard.component.spec.ts" region="router-harness"></code-example>
|
||||
|
||||
<code-example header="app/dashboard/dashboard.component.spec.ts (spies)" path="testing/src/app/dashboard/dashboard.component.spec.ts" region="router-spy"></code-example>
|
||||
|
||||
The following test clicks the displayed hero and confirms that `Router.navigateByUrl` is called with the expected url.
|
||||
The following test clicks the displayed hero and confirms that we navigate to the expected URL.
|
||||
|
||||
<code-example header="app/dashboard/dashboard.component.spec.ts (navigate test)" path="testing/src/app/dashboard/dashboard.component.spec.ts" region="navigate-test"></code-example>
|
||||
|
||||
@@ -863,36 +854,9 @@ The [ActivatedRoute in action](guide/router-tutorial-toh#activated-route-in-acti
|
||||
|
||||
</div>
|
||||
|
||||
Tests can explore how the `HeroDetailComponent` responds to different `id` parameter values by manipulating the `ActivatedRoute` injected into the component's constructor.
|
||||
Tests can explore how the `HeroDetailComponent` responds to different `id` parameter values by navigating to different routes.
|
||||
|
||||
You know how to spy on the `Router` and a data service.
|
||||
|
||||
You'll take a different approach with `ActivatedRoute` because
|
||||
|
||||
* `paramMap` returns an `Observable` that can emit more than one value during a test
|
||||
* You need the router helper function, `convertToParamMap()`, to create a `ParamMap`
|
||||
* Other *routed component* tests need a test double for `ActivatedRoute`
|
||||
|
||||
These differences argue for a re-usable stub class.
|
||||
|
||||
#### `ActivatedRouteStub`
|
||||
|
||||
The following `ActivatedRouteStub` class serves as a test double for `ActivatedRoute`.
|
||||
|
||||
<code-example header="testing/activated-route-stub.ts (ActivatedRouteStub)" path="testing/src/testing/activated-route-stub.ts" region="activated-route-stub"></code-example>
|
||||
|
||||
Consider placing such helpers in a `testing` folder sibling to the `app` folder.
|
||||
This sample puts `ActivatedRouteStub` in `testing/activated-route-stub.ts`.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Consider writing a more capable version of this stub class with the [*marble testing library*](#marble-testing).
|
||||
|
||||
</div>
|
||||
|
||||
<a id="tests-w-test-double"></a>
|
||||
|
||||
#### Testing with `ActivatedRouteStub`
|
||||
#### Testing with the `RouterTestingHarness`
|
||||
|
||||
Here's a test demonstrating the component's behavior when the observed `id` refers to an existing hero:
|
||||
|
||||
@@ -907,21 +871,12 @@ Rely on your intuition for now.
|
||||
|
||||
When the `id` cannot be found, the component should re-route to the `HeroListComponent`.
|
||||
|
||||
The test suite setup provided the same router spy [described above](#routing-component) which spies on the router without actually navigating.
|
||||
The test suite setup provided the same router harness [described above](#routing-component).
|
||||
|
||||
This test expects the component to try to navigate to the `HeroListComponent`.
|
||||
|
||||
<code-example header="app/hero/hero-detail.component.spec.ts (bad id)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="route-bad-id"></code-example>
|
||||
|
||||
While this application doesn't have a route to the `HeroDetailComponent` that omits the `id` parameter, it might add such a route someday.
|
||||
The component should do something reasonable when there is no `id`.
|
||||
|
||||
In this implementation, the component should create and display a new hero.
|
||||
New heroes have `id=0` and a blank `name`.
|
||||
This test confirms that the component behaves as expected:
|
||||
|
||||
<code-example header="app/hero/hero-detail.component.spec.ts (no id)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="route-no-id" ></code-example>
|
||||
|
||||
## Nested component tests
|
||||
|
||||
Component templates often have nested components, whose templates might contain more components.
|
||||
@@ -932,8 +887,6 @@ The `AppComponent`, for example, displays a navigation bar with anchors and thei
|
||||
|
||||
<code-example header="app/app.component.html" path="testing/src/app/app.component.html"></code-example>
|
||||
|
||||
While the `AppComponent` *class* is empty, you might want to write unit tests to confirm that the links are wired properly to the `RouterLink` directives, perhaps for the reasons as explained in the [following section](#why-stubbed-routerlink-tests).
|
||||
|
||||
To validate the links, you don't need the `Router` to navigate and you don't need the `<router-outlet>` to mark where the `Router` inserts *routed components*.
|
||||
|
||||
The `BannerComponent` and `WelcomeComponent` \(indicated by `<app-banner>` and `<app-welcome>`\) are also irrelevant.
|
||||
@@ -966,8 +919,6 @@ Then declare them in the `TestBed` configuration next to the components, directi
|
||||
|
||||
The `AppComponent` is the test subject, so of course you declare the real version.
|
||||
|
||||
The `RouterLinkDirectiveStub`, [described later](#routerlink), is a test version of the real `RouterLink` that helps with the link tests.
|
||||
|
||||
The rest are stubs.
|
||||
|
||||
<a id="no-errors-schema"></a>
|
||||
@@ -980,7 +931,7 @@ In the second approach, add `NO_ERRORS_SCHEMA` to the `TestBed.schemas` metadata
|
||||
|
||||
The `NO_ERRORS_SCHEMA` tells the Angular compiler to ignore unrecognized elements and attributes.
|
||||
|
||||
The compiler recognizes the `<app-root>` element and the `routerLink` attribute because you declared a corresponding `AppComponent` and `RouterLinkDirectiveStub` in the `TestBed` configuration.
|
||||
The compiler recognizes the `<app-root>` element and the `routerLink` attribute because you declared a corresponding `AppComponent` and `RouterLink` in the `TestBed` configuration.
|
||||
|
||||
But the compiler won't throw an error when it encounters `<app-banner>`, `<app-welcome>`, or `<router-outlet>`.
|
||||
It simply renders them as empty tags and the browser ignores them.
|
||||
@@ -1003,31 +954,7 @@ In practice you will combine the two techniques in the same setup, as seen in th
|
||||
|
||||
<code-example header="app/app.component.spec.ts (mixed setup)" path="testing/src/app/app.component.spec.ts" region="mixed-setup"></code-example>
|
||||
|
||||
The Angular compiler creates the `BannerStubComponent` for the `<app-banner>` element and applies the `RouterLinkStubDirective` to the anchors with the `routerLink` attribute, but it ignores the `<app-welcome>` and `<router-outlet>` tags.
|
||||
|
||||
<a id="routerlink"></a>
|
||||
|
||||
## Components with `RouterLink`
|
||||
|
||||
The real `RouterLinkDirective` is quite complicated and entangled with other components and directives of the `RouterModule`.
|
||||
It requires challenging setup to mock and use in tests.
|
||||
|
||||
The `RouterLinkDirectiveStub` in this sample code replaces the real directive with an alternative version designed to validate the kind of anchor tag wiring seen in the `AppComponent` template.
|
||||
|
||||
<code-example header="testing/router-link-directive-stub.ts (RouterLinkDirectiveStub)" path="testing/src/testing/router-link-directive-stub.ts" region="router-link"></code-example>
|
||||
|
||||
The URL bound to the `[routerLink]` attribute flows in to the directive's `linkParams` property.
|
||||
|
||||
The `HostListener` wires the click event of the host element \(the `<a>` anchor elements in `AppComponent`\) to the stub directive's `onClick` method.
|
||||
|
||||
Clicking the anchor should trigger the `onClick()` method, which sets the stub's telltale `navigatedTo` property.
|
||||
Tests inspect `navigatedTo` to confirm that clicking the anchor sets the expected route definition.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
Whether the router is configured properly to navigate with that route definition is a question for a separate set of tests.
|
||||
|
||||
</div>
|
||||
The Angular compiler creates the `BannerStubComponent` for the `<app-banner>` element and applies the `RouterLink` to the anchors with the `routerLink` attribute, but it ignores the `<app-welcome>` and `<router-outlet>` tags.
|
||||
|
||||
<a id="by-directive"></a>
|
||||
<a id="inject-directive"></a>
|
||||
@@ -1054,39 +981,6 @@ Here are some tests that confirm those links are wired to the `routerLink` direc
|
||||
|
||||
<code-example header="app/app.component.spec.ts (selected tests)" path="testing/src/app/app.component.spec.ts" region="tests"></code-example>
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
The "click" test *in this example* is misleading.
|
||||
It tests the `RouterLinkDirectiveStub` rather than the *component*.
|
||||
This is a common failing of directive stubs.
|
||||
|
||||
It has a legitimate purpose in this guide.
|
||||
It demonstrates how to find a `RouterLink` element, click it, and inspect a result, without engaging the full router machinery.
|
||||
This is a skill you might need to test a more sophisticated component, one that changes the display, re-calculates parameters, or re-arranges navigation options when the user clicks the link.
|
||||
|
||||
</div>
|
||||
|
||||
<a id="why-stubbed-routerlink-tests"></a>
|
||||
|
||||
#### What good are these tests?
|
||||
|
||||
Stubbed `RouterLink` tests can confirm that a component with links and an outlet is set up properly, that the component has the links it should have, and that they are all pointing in the expected direction.
|
||||
These tests do not concern whether the application will succeed in navigating to the target component when the user clicks a link.
|
||||
|
||||
Stubbing the RouterLink and RouterOutlet is the best option for such limited testing goals.
|
||||
Relying on the real router would make them brittle.
|
||||
They could fail for reasons unrelated to the component.
|
||||
For example, a navigation guard could prevent an unauthorized user from visiting the `HeroListComponent`.
|
||||
That's not the fault of the `AppComponent` and no change to that component could cure the failed test.
|
||||
|
||||
A *different* battery of tests can explore whether the application navigates as expected in the presence of conditions that influence guards such as whether the user is authenticated and authorized.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
A future guide update explains how to write such tests with the `RouterTestingModule`.
|
||||
|
||||
</div>
|
||||
|
||||
<a id="page-object"></a>
|
||||
|
||||
## Use a `page` object
|
||||
@@ -1126,9 +1020,6 @@ A `createComponent` method creates a `page` object and fills in the blanks once
|
||||
|
||||
<code-example header="app/hero/hero-detail.component.spec.ts (createComponent)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="create-component"></code-example>
|
||||
|
||||
The [`HeroDetailComponent` tests](#tests-w-test-double) in an earlier section demonstrate how `createComponent` and `page` keep the tests short and *on message*.
|
||||
There are no distractions: no waiting for promises to resolve and no searching the DOM for element values to compare.
|
||||
|
||||
Here are a few more `HeroDetailComponent` tests to reinforce the point.
|
||||
|
||||
<code-example header="app/hero/hero-detail.component.spec.ts (selected tests)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="selected-tests"></code-example>
|
||||
@@ -1263,8 +1154,8 @@ In addition to the support it receives from the default testing module `CommonMo
|
||||
|
||||
* `NgModel` and friends in the `FormsModule` to enable two-way data binding
|
||||
* The `TitleCasePipe` from the `shared` folder
|
||||
* The Router services that these tests are stubbing out
|
||||
* The Hero data access services that are also stubbed out
|
||||
* The Router services
|
||||
* The Hero data access services
|
||||
|
||||
One approach is to configure the testing module from the individual pieces as in this example:
|
||||
|
||||
@@ -1297,7 +1188,6 @@ Try a test configuration that imports the `HeroModule` like this one:
|
||||
|
||||
<code-example header="app/hero/hero-detail.component.spec.ts (HeroModule setup)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="setup-hero-module"></code-example>
|
||||
|
||||
That's *really* crisp.
|
||||
Only the *test doubles* in the `providers` remain.
|
||||
Even the `HeroDetailComponent` declaration is gone.
|
||||
|
||||
|
||||
@@ -1,3 +1,28 @@
|
||||
# Understanding communicating with backend services using HTTP
|
||||
|
||||
@reviewed 2022-10-06
|
||||
Most front-end applications need to communicate with a server over the HTTP protocol, to download or upload data and access other back-end services. Angular provides a client HTTP API for Angular applications, the `HttpClient` service class in `@angular/common/http`.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before working with the `HttpClientModule`, you should have a basic understanding of the following:
|
||||
|
||||
* TypeScript programming
|
||||
* Usage of the HTTP protocol
|
||||
* Angular application-design fundamentals, as described in [Angular Concepts](guide/architecture)
|
||||
* Observable techniques and operators.
|
||||
See the [Observables guide](guide/observables).
|
||||
|
||||
## HTTP client service features
|
||||
|
||||
The HTTP client service offers the following major features.
|
||||
|
||||
* The ability to request [typed response objects](guide/http-request-data-from-server)
|
||||
* Streamlined [error handling](guide/http-handle-request-errors)
|
||||
* [Testability](guide/http-test-requests) features
|
||||
* Request and response [interception](guide/http-intercept-requests-and-responses)
|
||||
|
||||
## What's next
|
||||
|
||||
* [Setup for server communication](guide/http-server-communication)
|
||||
|
||||
@reviewed 2023-03-14
|
||||
|
||||
@@ -112,9 +112,6 @@ If you throttle your network speed so that the client-side scripts take longer t
|
||||
* The search box on the Dashboard page is ignored
|
||||
* The *Back* and *Save* buttons on the Details page don't work
|
||||
|
||||
User events other than `routerLink` clicks aren't supported.
|
||||
You must wait for the full client application to bootstrap and run, or buffer the events using libraries like [preboot](https://github.com/angular/preboot), which lets you replay these events once the client-side scripts load.
|
||||
|
||||
The transition from the server-rendered application to the client application happens quickly on a development machine, but you should always test your applications in real-world scenarios.
|
||||
|
||||
You can simulate a slower network to see the transition more clearly as follows:
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Version compatibility
|
||||
|
||||
The following tables describe the versions of Node.js, TypeScript, and RxJS that each version of Angular requires. This information is collected from Angular's [package.json](https://unpkg.com/browse/@angular/core/package.json) file.
|
||||
|
||||
## Actively supported versions
|
||||
|
||||
This table covers [Angular versions under long-term support (LTS)](guide/releases#actively-supported-versions).
|
||||
|
||||
| Angular | Node.js | TypeScript | RxJS |
|
||||
| ------------------ | ------------------------------------ | -------------- | ------------------ |
|
||||
| 15.2.x | ^14.20.0 \|\| ^16.13.0 \|\| ^18.10.0 | >=4.8.2 <5.0.0 | ^6.5.3 \|\| ^7.4.0 |
|
||||
| 15.1.x | ^14.20.0 \|\| ^16.13.0 \|\| ^18.10.0 | >=4.8.2 <5.0.0 | ^6.5.3 \|\| ^7.4.0 |
|
||||
| 15.0.x | ^14.20.0 \|\| ^16.13.0 \|\| ^18.10.0 | ~4.8.2 | ^6.5.3 \|\| ^7.4.0 |
|
||||
| 14.3.x | ^14.15.0 \|\| ^16.10.0 | >=4.6.2 <4.9.0 | ^6.5.3 \|\| ^7.4.0 |
|
||||
| 14.2.x | ^14.15.0 \|\| ^16.10.0 | >=4.6.2 <4.9.0 | ^6.5.3 \|\| ^7.4.0 |
|
||||
| 14.0.x \|\| 14.1.x | ^14.15.0 \|\| ^16.10.0 | >=4.6.2 <4.8.0 | ^6.5.3 \|\| ^7.4.0 |
|
||||
| 13.3.x | ^12.20.0 \|\| ^14.15.0 \|\| ^16.10.0 | >=4.4.3 <4.7.0 | ^6.5.3 \|\| ^7.4.0 |
|
||||
| 13.1.x \|\| 13.2.x | ^12.20.0 \|\| ^14.15.0 \|\| ^16.10.0 | >=4.4.3 <4.6.0 | ^6.5.3 \|\| ^7.4.0 |
|
||||
| 13.0.x | ^12.20.0 \|\| ^14.15.0 \|\| ^16.10.0 | ~4.4.3 | ^6.5.3 \|\| ^7.4.0 |
|
||||
|
||||
## Unsupported Angular versions
|
||||
|
||||
This table covers Angular versions that are no longer under long-term support (LTS). This information was correct when each version went out of LTS and is provided without any further guarantees. It is listed here for historical reference.
|
||||
|
||||
| Angular | Angular CLI | Node.js | TypeScript | RxJS |
|
||||
| --------------------------- | ---------------- | ---------------------- | -------------- | ------------------ |
|
||||
| 12.2.x | 12.2.x | ^12.14.0 \|\| ^14.15.0 | >=4.2.3 <4.4.0 | ^6.5.3 \|\| ^7.0.0 |
|
||||
| 12.1.x | 12.1.x | ^12.14.0 \|\| ^14.15.0 | >=4.2.3 <4.4.0 | ^6.5.3 |
|
||||
| 12.0.x | 12.0.x | ^12.14.0 \|\| ^14.15.0 | ~4.2.3 | ^6.5.3 |
|
||||
| 11.2.x | 11.2.x | ^10.13.0 \|\| ^12.11.0 | >=4.0.0 <4.2.0 | ^6.5.3 |
|
||||
| 11.1.x | 11.1.x | ^10.13.0 \|\| ^12.11.0 | >=4.0.0 <4.2.0 | ^6.5.3 |
|
||||
| 11.0.x | 11.0.x | ^10.13.0 \|\| ^12.11.0 | ~4.0.0 | ^6.5.3 |
|
||||
| 10.2.x | 10.2.x | ^10.13.0 \|\| ^12.11.0 | >=3.9.0 <4.1.0 | ^6.5.3 |
|
||||
| 10.1.x | 10.1.x | ^10.13.0 \|\| ^12.11.0 | >=3.9.0 <4.1.0 | ^6.5.3 |
|
||||
| 10.0.x | 10.0.x | ^10.13.0 \|\| ^12.11.0 | ~3.9.0 | ^6.5.3 |
|
||||
| 9.1.x | 9.1.x | ^10.13.0 \|\| ^12.11.0 | >=3.6.0 <3.9.0 | ^6.5.3 |
|
||||
| 9.0.x | 9.0.x | ^10.13.0 \|\| ^12.11.0 | >=3.6.0 <3.8.0 | ^6.5.3 |
|
||||
| 8.2.x | 8.3.x | ^10.9.0 | >=3.5.3 <3.6.0 | ^6.4.0 |
|
||||
| 8.2.x | 8.2.x | ^10.9.0 | >=3.4.2 | ^6.4.0 |
|
||||
| 8.1.x | 8.1.x | ^10.9.0 | ~3.4.2 | ^6.4.0 |
|
||||
| 8.0.x | 8.0.x | ^10.9.0 | ~3.4.2 | ^6.4.0 |
|
||||
| 7.2.x | 7.3.x | ^8.9.0 \|\| ^10.9.0 | ~3.2.2 | ^6.0.0 |
|
||||
| 7.2.x | 7.2.x | ^8.9.0 \|\| ^10.9.0 | ~3.2.2 | ^6.0.0 |
|
||||
| 7.1.x | 7.1.x | ^8.9.0 \|\| ^10.9.0 | ~3.1.3 | ^6.0.0 |
|
||||
| 7.0.x | 7.0.x | ^8.9.0 \|\| ^10.9.0 | ~3.1.3 | ^6.0.0 |
|
||||
| 6.1.x | 6.2.x | ^8.9.0 | ~2.9.2 | ^6.0.0 |
|
||||
| 6.1.x | 6.1.x | ^8.9.0 | ~2.7.2 | ^6.0.0 |
|
||||
| 6.0.x | 6.0.x | ^8.9.0 | ~2.7.2 | ^6.0.0 |
|
||||
| 5.2.x | 1.6.x \|\| 1.7.x | ^6.9.0 \|\| ^8.9.0 | ~2.5.0 | ^5.5.0 |
|
||||
| 5.1.x | 1.5.x | ^6.9.0 \|\| ^8.9.0 | >=2.4.0 <2.6.0 | ^5.5.0 |
|
||||
| 5.0.x | 1.5.x | ^6.9.0 \|\| ^8.9.0 | ~2.4.0 | ^5.5.0 |
|
||||
| 4.2.x \|\| 4.3.x \|\| 4.4.x | 1.4.x | ^6.9.0 \|\| ^8.9.0 | ~2.4.0 | ^5.0.1 |
|
||||
| 4.2.x \|\| 4.3.x \|\| 4.4.x | 1.3.x | ^6.9.0 | ~2.4.0 | ^5.0.1 |
|
||||
| 4.0.x \|\| 4.1.x | 1.2.x | ^6.9.0 | ~2.3.0 | ^5.0.1 |
|
||||
| >=4.0.0 <4.2.0 | 1.1.x | ^6.9.0 | ~2.3.0 | ^5.0.1 |
|
||||
| >=4.0.0 <4.2.0 | 1.0.x | ^6.9.0 | ~2.2.0 | ^5.0.1 |
|
||||
| 2.x | - | ^6.9.0 | ~2.0.0 | ^5.0.1 |
|
||||
@@ -243,12 +243,14 @@ Some extra options can only be set through the configuration file, either by dir
|
||||
| `scripts` | An object containing JavaScript script files to add to the global context of the project. The scripts are loaded exactly as if you had added them in a `<script>` tag inside `index.html`. See more in the [Styles and scripts configuration](#style-script-config) section. |
|
||||
| `budgets` | Default size-budget type and thresholds for all or parts of your application. You can configure the builder to report a warning or an error when the output reaches or exceeds a threshold size. See [Configure size budgets](guide/build#configure-size-budgets). \(Not available in `test` section.\) |
|
||||
| `fileReplacements` | An object containing files and their compile-time replacements. See more in [Configure target-specific file replacements](guide/build#configure-target-specific-file-replacements). |
|
||||
`index` | Configures the generation of the application's HTML index. See more in [Index configuration](#index-config). \(Only available in `browser` section.\) | |
|
||||
|
||||
|
||||
<a id="complex-config"></a>
|
||||
|
||||
## Complex configuration values
|
||||
|
||||
The `assets`, `styles`, and `scripts` options can have either simple path string values, or object values with specific fields.
|
||||
The `assets`, `index`, `styles`, and `scripts` options can have either simple path string values, or object values with specific fields.
|
||||
The `sourceMap` and `optimization` options can be set to a simple Boolean value with a command flag. They can also be given a complex value using the configuration file.
|
||||
|
||||
The following sections provide more details of how these complex values are used in each case.
|
||||
@@ -514,6 +516,23 @@ These are useful if you only want source maps to map error stack traces in error
|
||||
|
||||
</div>
|
||||
|
||||
<a id="index-config"></a>
|
||||
|
||||
### Index configuration
|
||||
|
||||
Configures the generation of the application's HTML index.
|
||||
|
||||
The `index` option can be either a String or an Object for more fine-tune configuration.
|
||||
|
||||
When supplying the value as a String the filename of the specified path will be used for the generated file and will be created in the root of the application's configured output path.
|
||||
|
||||
#### Index options
|
||||
| Options | Details | Value type | Default value |
|
||||
|:--- |:--- |:--- |:--- |
|
||||
| `input` | The path of a file to use for the application's generated HTML index. | `string` | |
|
||||
| `output` | The output path of the application's generated HTML index file. The full provided path will be used and will be considered relative to the application's configured output path. | `string` | `index.html` |
|
||||
|
||||
|
||||
<!-- links -->
|
||||
|
||||
[AioGuideI18nCommonMerge]: guide/i18n-common-merge "Common Internationalization task #6: Merge translations into the application | Angular"
|
||||
@@ -522,4 +541,4 @@ These are useful if you only want source maps to map error stack traces in error
|
||||
|
||||
<!-- end links -->
|
||||
|
||||
@reviewed 2022-02-28
|
||||
@reviewed 2022-02-28
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 146 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 103 KiB |
@@ -116,6 +116,13 @@
|
||||
"twitter": "armandotrue",
|
||||
"bio": "Armen is a senior Angular developer from Armenia, tech writer, speaker, mentor and a Google Developer Expert for Angular."
|
||||
},
|
||||
"arturovt": {
|
||||
"name": "Artur Androsovych",
|
||||
"picture": "artur-androsovych.jpg",
|
||||
"groups": ["GDE"],
|
||||
"website": "https://ng-guru.io",
|
||||
"bio": "Artur is an Angular expert and OSS core developer of various projects as NGXS, NG-ZORRO, single-spa, ngneat, and RxAngular. He focuses on runtime performance and has taught teams about Angular internals for the past few years."
|
||||
},
|
||||
"atscott": {
|
||||
"name": "Andrew Scott",
|
||||
"picture": "andrewscott.jpg",
|
||||
@@ -601,6 +608,14 @@
|
||||
"bio": "Suguru is a community-loving Frontend developer and a lead of Angular Japan User Group. He organizes the largest Angular event in Japan (ng-japan). And he is a contributor to Angular by sending patches, writing, speaking, and localizing resources in Japanese.",
|
||||
"groups": ["GDE"]
|
||||
},
|
||||
"laranewsom": {
|
||||
"name": "Lara Newsom",
|
||||
"picture": "laranewsom.jpg",
|
||||
"twitter": "laranerdsom",
|
||||
"website": "https://www.linkedin.com/in/lara-newsom",
|
||||
"bio": "Lara is a Software Engineering Technical Leader on the Customer Experience Angular Team at Cisco. She is based in Des Moines, Iowa. In addition to speaking at conferences and talking about Angular and related technologies on the Angular Plus Show Podcast, Lara loves traveling with her husband and two teens. Much to the disappointment of her own two cats, Lara also enjoys fostering orphaned kittens. ",
|
||||
"groups": ["GDE"]
|
||||
},
|
||||
"leonardozizzamia": {
|
||||
"name": "Leonardo Zizzamia",
|
||||
"picture": "leonardo.jpg",
|
||||
|
||||
@@ -1132,5 +1132,89 @@
|
||||
"start": "2022-12-06"
|
||||
},
|
||||
"name": "Angular Contributor Days"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-01-24"
|
||||
},
|
||||
"name": "Online Meetup: The Future of Angular"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-02-02"
|
||||
},
|
||||
"name": "Angular Zurich Meetup"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-02-08"
|
||||
},
|
||||
"name": "JSWorld"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-02-23"
|
||||
},
|
||||
"name": "Agent Conf"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-03-24"
|
||||
},
|
||||
"name": "ng-be"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-04-25"
|
||||
},
|
||||
"name": "CityJS Brazil"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-05-04"
|
||||
},
|
||||
"name": "Devoxx Greece"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-05-18"
|
||||
},
|
||||
"name": "JSHeroes"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-05-10"
|
||||
},
|
||||
"name": "Google I/O"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-06-01"
|
||||
},
|
||||
"name": "JSNation"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-06-02"
|
||||
},
|
||||
"name": "JSConf India"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-06-14"
|
||||
},
|
||||
"name": "ng-conf"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-11-08"
|
||||
},
|
||||
"name": "NGPoland"
|
||||
},
|
||||
{
|
||||
"date": {
|
||||
"start": "2023-11-09"
|
||||
},
|
||||
"name": "JSPoland"
|
||||
}
|
||||
]
|
||||
@@ -1,6 +1,6 @@
|
||||
<h1 class="no-toc">Your first Angular app</h1>
|
||||
|
||||
A few lines of TypeScript are all it takes to create your first Angular app. As you your app grows, you can separate the markup and code into different files.
|
||||
A few lines of TypeScript are all it takes to create your first Angular app. As your app grows, you can separate the markup and code into different files.
|
||||
|
||||
## Try your first Angular app
|
||||
|
||||
@@ -41,7 +41,7 @@ To give your component a reset button that sets the counter back to 0:
|
||||
|
||||
1. Click **Add one** several times and then click **Reset**. The counter value should return to zero.
|
||||
|
||||
The new line adds a new `<button>` element. When the `click` event occurs in the button, the TypeScript code in the double-quotes sets the `count` property to `0`.
|
||||
The new line adds a new `<button>` element. When the `click` event occurs in the button, the TypeScript code in the double quotes sets the `count` property to `0`.
|
||||
|
||||
You can also add styles to your new component.
|
||||
|
||||
@@ -55,7 +55,7 @@ You can also add styles to your new component.
|
||||
|
||||
</code-example>
|
||||
|
||||
1. The buttons in your new Angular app should now have bold text and rounded corner.
|
||||
1. The buttons in your new Angular app should now have bold text and rounded corners.
|
||||
|
||||
### Create a new Angular app from the command line
|
||||
|
||||
|
||||
@@ -587,8 +587,8 @@
|
||||
"resources": {
|
||||
"-KLIzGEp8Mh5W-FkiQnL": {
|
||||
"desc": "A no-nonsense beginner's guide to building web applications with Angular and TypeScript",
|
||||
"title": "Learning Angular - Third Edition",
|
||||
"url": "https://www.packtpub.com/product/learning-angular-third-edition/9781839210662"
|
||||
"title": "Learning Angular - Fourth Edition",
|
||||
"url": "https://www.amazon.com/dp/1803240601"
|
||||
},
|
||||
"3ab": {
|
||||
"desc": "More than 15 books from O'Reilly about Angular",
|
||||
@@ -674,7 +674,7 @@
|
||||
"angular-projects": {
|
||||
"title": "Angular Projects - Second Edition",
|
||||
"desc": "Build modern web apps by exploring Angular with 10 different projects and cutting-edge technologies",
|
||||
"url": "https://www.packtpub.com/product/angular-projects-second-edition/9781800205260"
|
||||
"url": "https://www.amazon.com/dp/1800205260"
|
||||
},
|
||||
"rangle-angular-training-book": {
|
||||
"title": "Rangle’s Angular Training Book",
|
||||
|
||||
@@ -312,9 +312,20 @@
|
||||
"tooltip": "A list of developer guides for building Angular applications."
|
||||
},
|
||||
{
|
||||
"url": "guide/standalone-components",
|
||||
"title": "Standalone components",
|
||||
"tooltip": "Standalone components, directives, and pipes"
|
||||
"title": "Standalone",
|
||||
"tooltip": "Learn about Angular's standalone APIs and how to convert your application to them.",
|
||||
"children": [
|
||||
{
|
||||
"url": "guide/standalone-components",
|
||||
"title": "Standalone components",
|
||||
"tooltip": "Standalone components, directives, and pipes"
|
||||
},
|
||||
{
|
||||
"url": "guide/standalone-migration",
|
||||
"title": "Migrating to standalone",
|
||||
"tooltip": "Migrate your application to Angular's standalone APIs"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Change detection",
|
||||
@@ -869,6 +880,11 @@
|
||||
"title": "Release practices",
|
||||
"tooltip": "Angular versioning, release, support, and deprecation policies and practices."
|
||||
},
|
||||
{
|
||||
"url": "guide/versions",
|
||||
"title": "Version compatibility",
|
||||
"tooltip": "Angular, Node.js, TypeScript, and RxJS version compatibility."
|
||||
},
|
||||
{
|
||||
"url": "guide/browser-support",
|
||||
"title": "Browser support",
|
||||
|
||||
@@ -195,7 +195,7 @@ This section walks you through creating a child component, `ProductAlertsCompone
|
||||
|
||||
<code-example format="shell" language="shell">
|
||||
|
||||
`ng generate component product-alerts`
|
||||
ng generate component product-alerts
|
||||
|
||||
</code-example>
|
||||
|
||||
|
||||
@@ -329,7 +329,7 @@ This template binds directly to the component's `messageService`.
|
||||
|
||||
The messages look better after you add the private CSS styles to `messages.component.css` as listed in one of the ["final code review"](#final-code-review) tabs below.
|
||||
|
||||
## Add messages to hero service
|
||||
## Add MessageService to HeroesComponent
|
||||
|
||||
The following example shows how to display a history of each time the user clicks on a hero.
|
||||
This helps when you get to the next section on [Routing](tutorial/tour-of-heroes/toh-pt5).
|
||||
|
||||
@@ -206,7 +206,7 @@ This `getHeroes()` returns the sliced list of heroes at positions 1 and 5, retur
|
||||
|
||||
To navigate to the dashboard, the router needs an appropriate route.
|
||||
|
||||
Import the `DashboardComponent` in the `app-routing-module.ts` file.
|
||||
Import the `DashboardComponent` in the `app-routing.module.ts` file.
|
||||
|
||||
<code-example header="src/app/app-routing.module.ts (import DashboardComponent)" path="toh-pt5/src/app/app-routing.module.ts" region="import-dashboard"></code-example>
|
||||
|
||||
@@ -251,7 +251,7 @@ The user should be able to get to these details in three ways.
|
||||
1. By clicking a hero in the heroes list.
|
||||
1. By pasting a "deep link" URL into the browser address bar that identifies the hero to display.
|
||||
|
||||
This section enables navigation to the `HeroDetailComponent` and liberate it from the `HeroesComponent`.
|
||||
This section enables navigation to the `HeroDetailComponent` and liberates it from the `HeroesComponent`.
|
||||
|
||||
### Delete *hero details* from `HeroesComponent`
|
||||
|
||||
@@ -299,7 +299,7 @@ The hero items in the `HeroesComponent` are `<li>` elements whose click events a
|
||||
|
||||
<code-example header="src/app/heroes/heroes.component.html (list with onSelect)" path="toh-pt4/src/app/heroes/heroes.component.html" region="list"></code-example>
|
||||
|
||||
Remove the `<li>` back to just its `*ngFor`.
|
||||
Remove the inner HTML of `<li>`.
|
||||
Wrap the badge and name in an anchor `<a>` element.
|
||||
Add a `routerLink` attribute to the anchor that's the same as in the dashboard template.
|
||||
|
||||
|
||||
@@ -179,10 +179,10 @@ Because each service method returns a different kind of `Observable` result, `ha
|
||||
|
||||
### Tap into the Observable
|
||||
|
||||
The `HeroService` methods taps into the flow of observable values and send a message, using the `log()` method, to the message area at the bottom of the page.
|
||||
The `getHero()` method taps into the flow of observable values and sends a message, using the `log()` method, to the message area at the bottom of the page.
|
||||
|
||||
The RxJS `tap()` operator enables this ability by looking at the observable values, doing something with those values, and passing them along.
|
||||
The `tap()` call back doesn't access the values themselves.
|
||||
The `tap()` callback doesn't access the values themselves.
|
||||
|
||||
Here is the final version of `getHeroes()` with the `tap()` that logs the operation.
|
||||
|
||||
@@ -422,7 +422,7 @@ The `searchTerms` becomes an `Observable` emitting a steady stream of search ter
|
||||
|
||||
### Chaining RxJS operators
|
||||
|
||||
Passing a new search term directly to the `searchHeroes()` after every user keystroke creates excessive HTTP requests, which taxes server resources and burning through data plans.
|
||||
Passing a new search term directly to the `searchHeroes()` after every user keystroke creates excessive HTTP requests, which taxes server resources and burns through data plans.
|
||||
|
||||
Instead, the `ngOnInit()` method pipes the `searchTerms` observable through a sequence of RxJS operators that reduce the number of calls to the `searchHeroes()`. Ultimately, this returns an observable of timely hero search results where each one is a `Hero[]`.
|
||||
|
||||
|
||||
+9
-9
@@ -55,20 +55,20 @@
|
||||
},
|
||||
"//engines-comment": "If applicable, also update /package.json and /aio/tools/examples/shared/package.json",
|
||||
"engines": {
|
||||
"node": ">=14.17.1",
|
||||
"node": ">=16.14.0",
|
||||
"yarn": ">=1.22.4 <2",
|
||||
"npm": "Please use yarn instead of NPM to install dependencies"
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "15.2.0-next.4",
|
||||
"@angular/cdk": "15.2.0-next.4",
|
||||
"@angular/cdk": "15.2.0-rc.0",
|
||||
"@angular/common": "15.2.0-next.4",
|
||||
"@angular/compiler": "15.2.0-next.4",
|
||||
"@angular/core": "15.2.0-next.4",
|
||||
"@angular/elements": "15.2.0-next.4",
|
||||
"@angular/forms": "15.2.0-next.4",
|
||||
"@angular/material": "15.2.0-next.4",
|
||||
"@angular/material": "15.2.0-rc.0",
|
||||
"@angular/platform-browser": "15.2.0-next.4",
|
||||
"@angular/platform-browser-dynamic": "15.2.0-next.4",
|
||||
"@angular/router": "15.2.0-next.4",
|
||||
@@ -85,7 +85,7 @@
|
||||
"@angular-eslint/eslint-plugin": "^15.0.0",
|
||||
"@angular-eslint/eslint-plugin-template": "^15.0.0",
|
||||
"@angular-eslint/template-parser": "^15.0.0",
|
||||
"@angular/build-tooling": "https://github.com/angular/dev-infra-private-build-tooling-builds.git#8b49b0b38e67191b52367d8d0a6317d00b7d5100",
|
||||
"@angular/build-tooling": "https://github.com/angular/dev-infra-private-build-tooling-builds.git#d407e91db010f9eb72370b7509fc5e841ff8818b",
|
||||
"@angular/cli": "15.2.0-next.4",
|
||||
"@angular/compiler-cli": "15.2.0-next.4",
|
||||
"@bazel/bazelisk": "^1.7.5",
|
||||
@@ -99,8 +99,8 @@
|
||||
"@types/node": "^12.7.9",
|
||||
"@types/trusted-types": "^2.0.2",
|
||||
"@types/xregexp": "^4.3.0",
|
||||
"@typescript-eslint/eslint-plugin": "5.52.0",
|
||||
"@typescript-eslint/parser": "5.52.0",
|
||||
"@typescript-eslint/eslint-plugin": "5.54.1",
|
||||
"@typescript-eslint/parser": "5.54.1",
|
||||
"archiver": "^5.3.0",
|
||||
"assert": "^2.0.0",
|
||||
"canonical-path": "1.0.0",
|
||||
@@ -114,7 +114,7 @@
|
||||
"eslint": "^8.0.0",
|
||||
"eslint-plugin-import": "^2.23.4",
|
||||
"eslint-plugin-jasmine": "^4.1.2",
|
||||
"eslint-plugin-jsdoc": "^40.0.0",
|
||||
"eslint-plugin-jsdoc": "^41.0.0",
|
||||
"eslint-plugin-prefer-arrow": "^1.2.3",
|
||||
"find-free-port": "^2.0.0",
|
||||
"firebase-tools": "^11.0.0",
|
||||
@@ -145,7 +145,7 @@
|
||||
"lunr": "^2.3.9",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"protractor": "~7.0.0",
|
||||
"puppeteer-core": "19.5.2",
|
||||
"puppeteer-core": "19.7.2",
|
||||
"rehype-slug": "^4.0.1",
|
||||
"remark": "^12.0.0",
|
||||
"remark-html": "^13.0.0",
|
||||
@@ -158,7 +158,7 @@
|
||||
"ts-node": "^10.8.1",
|
||||
"tsec": "^0.2.2",
|
||||
"tslint": "~6.1.3",
|
||||
"typescript": "~4.8.0",
|
||||
"typescript": "~4.9.3",
|
||||
"uglify-js": "^3.13.3",
|
||||
"unist-util-filter": "^2.0.3",
|
||||
"unist-util-source": "^3.0.0",
|
||||
|
||||
@@ -164,6 +164,7 @@ describe('deploy-to-firebase/pre-deploy-actions:', () => {
|
||||
|
||||
describe('undo.checkPayloadSize()', () => {
|
||||
// This method is a no-op, so there is nothing to test.
|
||||
// eslint-disable-next-line jasmine/expect-single-argument
|
||||
it('does not need tests', () => expect().nothing());
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<header>
|
||||
<mat-toolbar #appToolbar color="primary" class="app-toolbar no-print" [class.transitioning]="isTransitioning">
|
||||
<mat-toolbar-row class="notification-container">
|
||||
<aio-notification notificationId="survey-january-2023" expirationDate="2023-03-30" [dismissOnContentClick]="true" (dismissed)="notificationDismissed()">
|
||||
<aio-notification notificationId="survey-january-2023" expirationDate="2023-02-15" [dismissOnContentClick]="true" (dismissed)="notificationDismissed()">
|
||||
<a href="https://goo.gle/angular-devsat-q1-2023">
|
||||
<mat-icon class="icon" svgIcon="insert_comment" aria-label="Announcement"></mat-icon>
|
||||
<span class="message">Help Angular by taking a <b>quick survey</b>!</span>
|
||||
@@ -67,7 +67,7 @@
|
||||
|
||||
<main class="sidenav-content" [id]="pageId">
|
||||
<div id="main-content" tabindex="-1"></div>
|
||||
<aio-mode-banner [mode]="deployment.mode" [version]="versionInfo"></aio-mode-banner>
|
||||
<aio-mode-banner *ngIf="versionInfo" [mode]="deployment.mode" [version]="versionInfo"></aio-mode-banner>
|
||||
<aio-doc-viewer [class.no-animations]="disableAnimations" [doc]="currentDocument" (docReady)="onDocReady()" (docRemoved)="onDocRemoved()" (docInserted)="onDocInserted()" (docRendered)="onDocRendered()">
|
||||
</aio-doc-viewer>
|
||||
<aio-dt *ngIf="dtOn" [(doc)]="currentDocument"></aio-dt>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user