docs: minor fixes (anchor tags, redundant whitespace, consistent code-snippets lang) (#21589)
PR Close #21589
This commit is contained in:
parent
1ce46b56f8
commit
bf248792eb
|
@ -79,13 +79,13 @@ there are fewer opportunities for injection attacks.
|
|||
|
||||
{@a compiler-options}
|
||||
|
||||
## Angular Compiler Options
|
||||
## Angular Compiler Options
|
||||
|
||||
You can control your app compilation by providing template compiler options in the `tsconfig.json` file along with the options supplied to the TypeScript compiler. The template compiler options are specified as members of
|
||||
`"angularCompilerOptions"` object as shown below:
|
||||
You can control your app compilation by providing template compiler options in the `tsconfig.json` file along with the options supplied to the TypeScript compiler. The template compiler options are specified as members of
|
||||
`"angularCompilerOptions"` object as shown below:
|
||||
|
||||
```json
|
||||
{
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
...
|
||||
|
@ -95,155 +95,155 @@ there are fewer opportunities for injection attacks.
|
|||
"preserveWhiteSpace": false,
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
}
|
||||
```
|
||||
|
||||
### *skipMetadataEmit*
|
||||
### *skipMetadataEmit*
|
||||
|
||||
This option tells the compiler not to produce `.metadata.json` files.
|
||||
The option is `false` by default.
|
||||
This option tells the compiler not to produce `.metadata.json` files.
|
||||
The option is `false` by default.
|
||||
|
||||
`.metadata.json` files contain infomration needed by the template compiler from a `.ts`
|
||||
file that is not included in the `.d.ts` file produced by the TypeScript compiler. This information contains,
|
||||
for example, the content of annotations (such as a component's template) which TypeScript
|
||||
emits to the `.js` file but not to the `.d.ts` file.
|
||||
`.metadata.json` files contain infomration needed by the template compiler from a `.ts`
|
||||
file that is not included in the `.d.ts` file produced by the TypeScript compiler. This information contains,
|
||||
for example, the content of annotations (such as a component's template) which TypeScript
|
||||
emits to the `.js` file but not to the `.d.ts` file.
|
||||
|
||||
This option should be set to `true` if using TypeScript's `--outFile` option, as the metadata files
|
||||
are not valid for this style of TypeScript output. It is not recommeded to use `--outFile` with
|
||||
Angular. Use a bundler, such as [webpack](https://webpack.js.org/), instead.
|
||||
This option should be set to `true` if using TypeScript's `--outFile` option, as the metadata files
|
||||
are not valid for this style of TypeScript output. It is not recommeded to use `--outFile` with
|
||||
Angular. Use a bundler, such as [webpack](https://webpack.js.org/), instead.
|
||||
|
||||
This option can also be set to `true` when using factory summaries as the factory summaries
|
||||
include a copy of the information that is in the `.metadata.json` file.
|
||||
This option can also be set to `true` when using factory summaries as the factory summaries
|
||||
include a copy of the information that is in the `.metadata.json` file.
|
||||
|
||||
### *strictMetadataEmit*
|
||||
### *strictMetadataEmit*
|
||||
|
||||
This option tells the template compiler to report an error to the `.metadata.json`
|
||||
file if `"skipMetadataEmit"` is `false` . This option is `false` by default. This should only be used when `"skipMetadataEmit"` is `false` and `"skipTemplateCodeGen"` is `true`.
|
||||
This option tells the template compiler to report an error to the `.metadata.json`
|
||||
file if `"skipMetadataEmit"` is `false` . This option is `false` by default. This should only be used when `"skipMetadataEmit"` is `false` and `"skipTemplateCodeGen"` is `true`.
|
||||
|
||||
It is intended to validate the `.metadata.json` files emitted for bundling with an `npm` package. The validation is overly strict and can emit errors for metadata that would never produce an error when used by the template compiler. You can choose to suppress the error emitted by this option for an exported symbol by including `@dynamic` in the comment documenting the symbol.
|
||||
It is intended to validate the `.metadata.json` files emitted for bundling with an `npm` package. The validation is overly strict and can emit errors for metadata that would never produce an error when used by the template compiler. You can choose to suppress the error emitted by this option for an exported symbol by including `@dynamic` in the comment documenting the symbol.
|
||||
|
||||
It is valid for `.metadata.json` files to contain errors. The template compiler reports these errors
|
||||
if the metadata is used to determine the contents of an annotation. The metadata
|
||||
collector cannot predict the symbols that are designed to use in an annotation, so it will preemptively
|
||||
include error nodes in the metadata for the exported symbols. The template compiler can then use the error
|
||||
nodes to report an error if these symbols are used. If the client of a library intends to use a symbol in an annotation, the template compiler will not normally report
|
||||
this until the client uses the symbol. This option allows detecting these errors during the build phase of
|
||||
the library and is used, for example, in producing Angular libraries themselves.
|
||||
It is valid for `.metadata.json` files to contain errors. The template compiler reports these errors
|
||||
if the metadata is used to determine the contents of an annotation. The metadata
|
||||
collector cannot predict the symbols that are designed to use in an annotation, so it will preemptively
|
||||
include error nodes in the metadata for the exported symbols. The template compiler can then use the error
|
||||
nodes to report an error if these symbols are used. If the client of a library intends to use a symbol in an annotation, the template compiler will not normally report
|
||||
this until the client uses the symbol. This option allows detecting these errors during the build phase of
|
||||
the library and is used, for example, in producing Angular libraries themselves.
|
||||
|
||||
### *skipTemplateCodegen*
|
||||
### *skipTemplateCodegen*
|
||||
|
||||
This option tells the compiler to suppress emitting `.ngfactory.js` and `.ngstyle.js` files. When set,
|
||||
this turns off most of the template compiler and disables reporting template diagnostics.
|
||||
This option can be used to instruct the
|
||||
template compiler to produce `.metadata.json` files for distribution with an `npm` package while
|
||||
avoiding the production of `.ngfactory.js` and `.ngstyle.js` files that cannot be distributed to
|
||||
`npm`.
|
||||
This option tells the compiler to suppress emitting `.ngfactory.js` and `.ngstyle.js` files. When set,
|
||||
this turns off most of the template compiler and disables reporting template diagnostics.
|
||||
This option can be used to instruct the
|
||||
template compiler to produce `.metadata.json` files for distribution with an `npm` package while
|
||||
avoiding the production of `.ngfactory.js` and `.ngstyle.js` files that cannot be distributed to
|
||||
`npm`.
|
||||
|
||||
### *strictInjectionParameters*
|
||||
### *strictInjectionParameters*
|
||||
|
||||
When set to `true`, this options tells the compiler to report an error for a parameter supplied
|
||||
whose injection type cannot be determined. When this value option is not provided or is `false`, constructor parameters of classes marked with `@Injectable` whose type cannot be resolved will
|
||||
produce a warning.
|
||||
When set to `true`, this options tells the compiler to report an error for a parameter supplied
|
||||
whose injection type cannot be determined. When this value option is not provided or is `false`, constructor parameters of classes marked with `@Injectable` whose type cannot be resolved will
|
||||
produce a warning.
|
||||
|
||||
*Note*: It is recommended to change this option explicitly to `true` as this option will default to `true` in the future.
|
||||
*Note*: It is recommended to change this option explicitly to `true` as this option will default to `true` in the future.
|
||||
|
||||
### *flatModuleOutFile*
|
||||
### *flatModuleOutFile*
|
||||
|
||||
When set to `true`, this option tells the template compiler to generate a flat module
|
||||
index of the given file name and the corresponding flat module metadata. Use this option when creating
|
||||
flat modules that are packaged similarly to `@angular/core` and `@angular/common`. When this option
|
||||
is used, the `package.json` for the library should refer
|
||||
to the generated flat module index instead of the library index file. With this
|
||||
option only one `.metadata.json` file is produced that contains all the metadata necessary
|
||||
for symbols exported from the library index. In the generated `.ngfactory.js` files, the flat
|
||||
module index is used to import symbols that includes both the public API from the library index
|
||||
as well as shrowded internal symbols.
|
||||
When set to `true`, this option tells the template compiler to generate a flat module
|
||||
index of the given file name and the corresponding flat module metadata. Use this option when creating
|
||||
flat modules that are packaged similarly to `@angular/core` and `@angular/common`. When this option
|
||||
is used, the `package.json` for the library should refer
|
||||
to the generated flat module index instead of the library index file. With this
|
||||
option only one `.metadata.json` file is produced that contains all the metadata necessary
|
||||
for symbols exported from the library index. In the generated `.ngfactory.js` files, the flat
|
||||
module index is used to import symbols that includes both the public API from the library index
|
||||
as well as shrowded internal symbols.
|
||||
|
||||
By default the `.ts` file supplied in the `files` field is assumed to be library index.
|
||||
If more than one `.ts` file is specified, `libraryIndex` is used to select the file to use.
|
||||
If more than one `.ts` file is supplied without a `libraryIndex`, an error is produced. A flat module
|
||||
index `.d.ts` and `.js` will be created with the given `flatModuleOutFile` name in the same
|
||||
location as the library index `.d.ts` file. For example, if a library uses
|
||||
`public_api.ts` file as the library index of the module, the `tsconfig.json` `files` field
|
||||
would be `["public_api.ts"]`. The `flatModuleOutFile` options could then be set to, for
|
||||
example `"index.js"`, which produces `index.d.ts` and `index.metadata.json` files. The
|
||||
library's `package.json`'s `module` field would be `"index.js"` and the `typings` field
|
||||
would be `"index.d.ts"`.
|
||||
By default the `.ts` file supplied in the `files` field is assumed to be library index.
|
||||
If more than one `.ts` file is specified, `libraryIndex` is used to select the file to use.
|
||||
If more than one `.ts` file is supplied without a `libraryIndex`, an error is produced. A flat module
|
||||
index `.d.ts` and `.js` will be created with the given `flatModuleOutFile` name in the same
|
||||
location as the library index `.d.ts` file. For example, if a library uses
|
||||
`public_api.ts` file as the library index of the module, the `tsconfig.json` `files` field
|
||||
would be `["public_api.ts"]`. The `flatModuleOutFile` options could then be set to, for
|
||||
example `"index.js"`, which produces `index.d.ts` and `index.metadata.json` files. The
|
||||
library's `package.json`'s `module` field would be `"index.js"` and the `typings` field
|
||||
would be `"index.d.ts"`.
|
||||
|
||||
### *flatModuleId*
|
||||
### *flatModuleId*
|
||||
|
||||
This option specifies the preferred module id to use for importing a flat module.
|
||||
References generated by the template compiler will use this module name when importing symbols
|
||||
from the flat module.
|
||||
This is only meaningful when `flatModuleOutFile` is also supplied. Otherwise the compiler ignores
|
||||
this option.
|
||||
This option specifies the preferred module id to use for importing a flat module.
|
||||
References generated by the template compiler will use this module name when importing symbols
|
||||
from the flat module.
|
||||
This is only meaningful when `flatModuleOutFile` is also supplied. Otherwise the compiler ignores
|
||||
this option.
|
||||
|
||||
### *generateCodeForLibraries*
|
||||
### *generateCodeForLibraries*
|
||||
|
||||
This option tells the template compiler to generate factory files (`.ngfactory.js` and `.ngstyle.js`)
|
||||
for `.d.ts` files with a corresponding `.metadata.json` file. This option defaults to
|
||||
`true`. When this option is `false`, factory files are generated only for `.ts` files.
|
||||
This option tells the template compiler to generate factory files (`.ngfactory.js` and `.ngstyle.js`)
|
||||
for `.d.ts` files with a corresponding `.metadata.json` file. This option defaults to
|
||||
`true`. When this option is `false`, factory files are generated only for `.ts` files.
|
||||
|
||||
This option should be set to `false` when using factory summaries.
|
||||
This option should be set to `false` when using factory summaries.
|
||||
|
||||
### *fullTemplateTypeCheck*
|
||||
### *fullTemplateTypeCheck*
|
||||
|
||||
This option tells the compiler to enable the [binding expression validation](#binding-expresion-validation)
|
||||
phase of the template compiler which uses TypeScript to validate binding expressions.
|
||||
This option tells the compiler to enable the [binding expression validation](#binding-expresion-validation)
|
||||
phase of the template compiler which uses TypeScript to validate binding expressions.
|
||||
|
||||
This option is `false` by default.
|
||||
This option is `false` by default.
|
||||
|
||||
*Note*: It is recommended to set this to `true` as this option will default to `true` in the future.
|
||||
*Note*: It is recommended to set this to `true` as this option will default to `true` in the future.
|
||||
|
||||
### *annotateForClosureCompiler*
|
||||
### *annotateForClosureCompiler*
|
||||
|
||||
This option tells the compiler to use [Tsickle](https://github.com/angular/tsickle) to annotate the emitted
|
||||
JavaScript with [JsDoc](http://usejsdoc.org/) comments needed by the
|
||||
[Closure Compiler](https://github.com/google/closure-compiler). This option defaults to `false`.
|
||||
This option tells the compiler to use [Tsickle](https://github.com/angular/tsickle) to annotate the emitted
|
||||
JavaScript with [JsDoc](http://usejsdoc.org/) comments needed by the
|
||||
[Closure Compiler](https://github.com/google/closure-compiler). This option defaults to `false`.
|
||||
|
||||
### *annotationsAs*
|
||||
### *annotationsAs*
|
||||
|
||||
Use this option to modify how the Angular specific annotations are emitted to improve tree-shaking. Non-Angular
|
||||
annotations and decorators are unnaffected. Default is `static fields`.
|
||||
Use this option to modify how the Angular specific annotations are emitted to improve tree-shaking. Non-Angular
|
||||
annotations and decorators are unnaffected. Default is `static fields`.
|
||||
|
||||
value | description
|
||||
----------------|-------------------------------------------------------------
|
||||
`decorators` | Leave the Decorators in-place. This makes compilation faster. TypeScript will emit calls to the __decorate helper. Use `--emitDecoratorMetadata` for runtime reflection. However, the resulting code will not properly tree-shake.
|
||||
`static fields` | Replace decorators with a static field in the class. Allows advanced tree-shakers like [Closure Compiler](https://github.com/google/closure-compiler) to remove unused classes.
|
||||
value | description
|
||||
----------------|-------------------------------------------------------------
|
||||
`decorators` | Leave the Decorators in-place. This makes compilation faster. TypeScript will emit calls to the __decorate helper. Use `--emitDecoratorMetadata` for runtime reflection. However, the resulting code will not properly tree-shake.
|
||||
`static fields` | Replace decorators with a static field in the class. Allows advanced tree-shakers like [Closure Compiler](https://github.com/google/closure-compiler) to remove unused classes.
|
||||
|
||||
### *trace*
|
||||
### *trace*
|
||||
|
||||
This tells the compiler to print extra information while compiling templates.
|
||||
This tells the compiler to print extra information while compiling templates.
|
||||
|
||||
### *enableLegacyTemplate*
|
||||
### *enableLegacyTemplate*
|
||||
|
||||
The use of `<template>` element was deprecated starting in Angular 4.0 in favor of using
|
||||
`<ng-template>` to avoid colliding with the DOM's element of the same name. Setting this option to
|
||||
`true` enables the use of the deprecated `<template>` element . This option
|
||||
is `false` by default. This option might be required by some third-party Angular libraries.
|
||||
The use of `<template>` element was deprecated starting in Angular 4.0 in favor of using
|
||||
`<ng-template>` to avoid colliding with the DOM's element of the same name. Setting this option to
|
||||
`true` enables the use of the deprecated `<template>` element . This option
|
||||
is `false` by default. This option might be required by some third-party Angular libraries.
|
||||
|
||||
### *disableExpressionLowering*
|
||||
### *disableExpressionLowering*
|
||||
|
||||
The Angular template compiler transforms code that is used, or could be used, in an annotation
|
||||
to allow it to be imported from template factory modules. See
|
||||
[metadata rewriting](#metadata-rewriting) for more information.
|
||||
The Angular template compiler transforms code that is used, or could be used, in an annotation
|
||||
to allow it to be imported from template factory modules. See
|
||||
[metadata rewriting](#metadata-rewriting) for more information.
|
||||
|
||||
Setting this option to `false` disables this rewriting, requiring the rewriting to be
|
||||
done manually.
|
||||
Setting this option to `false` disables this rewriting, requiring the rewriting to be
|
||||
done manually.
|
||||
|
||||
### *preserveWhitespaces*
|
||||
### *preserveWhitespaces*
|
||||
|
||||
This option tells the compiler whether to remove blank text nodes from compiled templates.
|
||||
This option is `true` by default.
|
||||
This option tells the compiler whether to remove blank text nodes from compiled templates.
|
||||
This option is `true` by default.
|
||||
|
||||
*Note*: It is recommended to set this explicitly to `false` as it emits smaller template factory modules and might be set to `false` by default in the future.
|
||||
*Note*: It is recommended to set this explicitly to `false` as it emits smaller template factory modules and might be set to `false` by default in the future.
|
||||
|
||||
### *allowEmptyCodegenFiles*
|
||||
### *allowEmptyCodegenFiles*
|
||||
|
||||
Tells the compiler to generate all the possible generated files even if they are empty. This option is
|
||||
`false` by default. This is an option used by `bazel` build rules and is needed to simplify
|
||||
how `bazel` rules track file dependencies. It is not recommended to use this option outside of the `bazel`
|
||||
rules.
|
||||
Tells the compiler to generate all the possible generated files even if they are empty. This option is
|
||||
`false` by default. This is an option used by `bazel` build rules and is needed to simplify
|
||||
how `bazel` rules track file dependencies. It is not recommended to use this option outside of the `bazel`
|
||||
rules.
|
||||
|
||||
## Angular Metadata and AOT
|
||||
|
||||
|
@ -353,7 +353,7 @@ and [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Re
|
|||
|
||||
Consider the following component decorator:
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
@Component({
|
||||
...
|
||||
providers: [{provide: server, useFactory: () => new Server()}]
|
||||
|
@ -367,7 +367,7 @@ When the compiler later interprets this node, it reports an error that invites y
|
|||
|
||||
You can fix the error by converting to this:
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
export function serverFactory() {
|
||||
return new Server();
|
||||
}
|
||||
|
@ -406,7 +406,7 @@ module-local `const` declarations and initialized `var` and `let` declarations,
|
|||
|
||||
Consider the following component definition:
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
const template = '<div>{{hero.name}}</div>';
|
||||
|
||||
@Component({
|
||||
|
@ -423,7 +423,7 @@ The compiler could not refer to the `template` constant because it isn't exporte
|
|||
But the _collector_ can _fold_ the `template` constant into the metadata definition by inlining its contents.
|
||||
The effect is the same as if you had written:
|
||||
|
||||
```TypeScript
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'app-hero',
|
||||
template: '<div>{{hero.name}}</div>'
|
||||
|
@ -437,7 +437,7 @@ There is no longer a reference to `template` and, therefore, nothing to trouble
|
|||
|
||||
You can take this example a step further by including the `template` constant in another expression:
|
||||
|
||||
```TypeScript
|
||||
```typescript
|
||||
const template = '<div>{{hero.name}}</div>';
|
||||
|
||||
@Component({
|
||||
|
@ -495,7 +495,7 @@ Decorated component class members must be public. You cannot make an `@Input()`
|
|||
|
||||
Data bound properties must also be public.
|
||||
|
||||
```TypeScript
|
||||
```typescript
|
||||
// BAD CODE - title is private
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
|
@ -547,7 +547,7 @@ methods that return an expression.
|
|||
|
||||
For example, consider the following function:
|
||||
|
||||
```TypeScript
|
||||
```typescript
|
||||
export function wrapInArray<T>(value: T): T[] {
|
||||
return [value];
|
||||
}
|
||||
|
@ -557,7 +557,7 @@ You can call the `wrapInArray` in a metadata definition because it returns the v
|
|||
|
||||
You might use `wrapInArray()` like this:
|
||||
|
||||
```TypeScript
|
||||
```typescript
|
||||
@NgModule({
|
||||
declarations: wrapInArray(TypicalComponent)
|
||||
})
|
||||
|
@ -566,7 +566,7 @@ export class TypicalModule {}
|
|||
|
||||
The compiler treats this usage as if you had written:
|
||||
|
||||
```TypeScript
|
||||
```typescript
|
||||
@NgModule({
|
||||
declarations: [TypicalComponent]
|
||||
})
|
||||
|
@ -580,7 +580,8 @@ The Angular [`RouterModule`](api/router/RouterModule) exports two macro static m
|
|||
Review the [source code](https://github.com/angular/angular/blob/master/packages/router/src/router_module.ts#L139 "RouterModule.forRoot source code")
|
||||
for these methods to see how macros can simplify configuration of complex [NgModules](guide/ngmodules).
|
||||
|
||||
{@ metadata-rewriting}
|
||||
{@a metadata-rewriting}
|
||||
|
||||
### Metadata rewriting
|
||||
|
||||
The compiler treats object literals containing the fields `useClass`, `useValue`, `useFactory`, and `data` specially. The compiler converts the expression initializing one of these fields into an exported variable, which replaces the expression. This process of rewriting these expressions removes all the restrictions on what can be in them because
|
||||
|
@ -590,7 +591,7 @@ the compiler doesn't need to know the expression's value—it just needs to
|
|||
|
||||
You might write something like:
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
class TypicalServer {
|
||||
|
||||
}
|
||||
|
@ -605,7 +606,7 @@ Without rewriting, this would be invalid because lambdas are not supported and `
|
|||
|
||||
To allow this, the compiler automatically rewrites this to something like:
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
class TypicalServer {
|
||||
|
||||
}
|
||||
|
@ -1146,7 +1147,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
|
|||
|
||||
For example, consider the following component:
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '{{person.addresss.street}}'
|
||||
|
@ -1183,7 +1184,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
|
|||
`Object is possibly 'undefined'` error in the template above, modify it to only emit the
|
||||
interpolation if the value of `person` is initialized as shown below:
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '<span *ngIf="person"> {{person.addresss.street}} </span>'
|
||||
|
@ -1202,7 +1203,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
|
|||
a static member marker that is a signal to the template compiler to treat them
|
||||
like `*ngIf`. This static member for `*ngIf` is:
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
public static ngIfUseIfTypeGuard: void;
|
||||
```
|
||||
|
||||
|
@ -1223,7 +1224,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
|
|||
way to describe this constraint to TypeScript and the template compiler, but the error
|
||||
is suppressed in the example by using `address!.street`.
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '<span *ngIf="person"> {{person.name}} lives on {{address!.street}} </span>'
|
||||
|
@ -1245,7 +1246,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
|
|||
In this example it is recommended to include the checking of `address`
|
||||
in the `*ngIf`as shown below:
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '<span *ngIf="person && address"> {{person.name}} lives on {{address.street}} </span>'
|
||||
|
@ -1271,7 +1272,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
|
|||
In the following example, the error `Property addresss does not exist` is suppressed
|
||||
by casting `person` to the `any` type.
|
||||
|
||||
```ts
|
||||
```typescript
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '{{$any(person).addresss.street}}'
|
||||
|
@ -1289,4 +1290,3 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
|
|||
* Macro-functions and macro-static methods.
|
||||
* Compiler errors related to metadata.
|
||||
* Validation of binding expressions
|
||||
|
||||
|
|
|
@ -14,7 +14,7 @@ By convention, it is usually called `AppModule`.
|
|||
|
||||
If you use the CLI to generate an app, the default `AppModule` is as follows:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
/* JavaScript imports */
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { NgModule } from '@angular/core';
|
||||
|
@ -78,7 +78,7 @@ this module and the other module imports this one.
|
|||
|
||||
An example of what goes into a declarations array follows:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
declarations: [
|
||||
YourComponent,
|
||||
YourPipe,
|
||||
|
@ -178,4 +178,3 @@ root module's `bootstrap` array.
|
|||
|
||||
For more on NgModules you're likely to see frequently in apps,
|
||||
see [Frequently Used Modules](#).
|
||||
|
||||
|
|
|
@ -821,7 +821,7 @@ Here's an embedded live example for this guide. It has a custom image created fr
|
|||
|
||||
<live-example embedded img="guide/docs-style-guide/docs-style-guide-plunker.png"></live-example>
|
||||
|
||||
<a id="anchors"></a>
|
||||
{@a anchors}
|
||||
|
||||
## Anchors
|
||||
|
||||
|
@ -861,12 +861,13 @@ Sometimes the section header text makes for an unattractive anchor. [This one](#
|
|||
|
||||
The greater danger is that **a future rewording of the header text would break** a link to this section.
|
||||
|
||||
For these reasons, it is often wise to add a custom anchor explicitly, just above the heading or text to which it applies, using the special`{@ name}` syntax like this.
|
||||
For these reasons, it is often wise to add a custom anchor explicitly, just above the heading or
|
||||
text to which it applies, using the special `{@a name}` syntax like this.
|
||||
|
||||
<code-example language="html">
|
||||
{@a ugly-anchors}
|
||||
|
||||
#### Ugly, long section header anchors
|
||||
#### Ugly, long section header anchors
|
||||
</code-example>
|
||||
|
||||
Now [link to that custom anchor name](#ugly-anchors) as you did before.
|
||||
|
|
|
@ -9,7 +9,7 @@ Additional benefits of `HttpClient` include testability support, strong typing o
|
|||
|
||||
Before you can use the `HttpClient`, you need to install the `HttpClientModule` which provides it. This can be done in your application module, and is only necessary once.
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
// app.module.ts:
|
||||
|
||||
import {NgModule} from '@angular/core';
|
||||
|
@ -48,7 +48,7 @@ The most common type of request applications make to a backend is to request JSO
|
|||
The `get()` method on `HttpClient` makes accessing this data straightforward.
|
||||
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
@Component(...)
|
||||
export class MyComponent implements OnInit {
|
||||
|
||||
|
@ -75,7 +75,7 @@ In the above example, the `data['results']` field access stands out because you
|
|||
You can, however, tell `HttpClient` what type the response will be, which is recommended.
|
||||
To do so, first you define an interface with the correct shape:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
interface ItemsResponse {
|
||||
results: string[];
|
||||
}
|
||||
|
@ -83,7 +83,7 @@ interface ItemsResponse {
|
|||
|
||||
Then, when you make the `HttpClient.get` call, pass a type parameter:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
http.get<ItemsResponse>('/api/items').subscribe(data => {
|
||||
// data is now an instance of type ItemsResponse, so you can do this:
|
||||
this.results = data.results;
|
||||
|
@ -94,7 +94,7 @@ http.get<ItemsResponse>('/api/items').subscribe(data => {
|
|||
|
||||
The response body doesn't return all the data you may need. Sometimes servers return special headers or status codes to indicate certain conditions, and inspecting those can be necessary. To do this, you can tell `HttpClient` you want the full response instead of just the body with the `observe` option:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
http
|
||||
.get<MyJsonData>('/data.json', {observe: 'response'})
|
||||
.subscribe(resp => {
|
||||
|
@ -116,7 +116,7 @@ What happens if the request fails on the server, or if a poor network connection
|
|||
|
||||
To handle it, add an error handler to your `.subscribe()` call:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
http
|
||||
.get<ItemsResponse>('/api/items')
|
||||
.subscribe(
|
||||
|
@ -137,7 +137,7 @@ There are two types of errors that can occur. If the backend returns an unsucces
|
|||
|
||||
In both cases, you can look at the `HttpErrorResponse` to figure out what happened.
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
http
|
||||
.get<ItemsResponse>('/api/items')
|
||||
.subscribe(
|
||||
|
@ -169,7 +169,7 @@ import 'rxjs/add/operator/retry';
|
|||
|
||||
Then, you can use it with HTTP Observables like this:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
http
|
||||
.get<ItemsResponse>('/api/items')
|
||||
// Retry this request up to 3 times.
|
||||
|
@ -182,7 +182,7 @@ http
|
|||
|
||||
Not all APIs return JSON data. Suppose you want to read a text file on the server. You have to tell `HttpClient` that you expect a textual response:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
http
|
||||
.get('/textfile.txt', {responseType: 'text'})
|
||||
// The Observable returned by get() is of type Observable<string>
|
||||
|
@ -200,7 +200,7 @@ In addition to fetching data from the server, `HttpClient` supports mutating req
|
|||
One common operation is to POST data to a server; for example when submitting a form. The code for
|
||||
sending a POST request is very similar to the code for GET:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
const body = {name: 'Brad'};
|
||||
|
||||
http
|
||||
|
@ -212,7 +212,7 @@ http
|
|||
|
||||
*Note the `subscribe()` method.* All Observables returned from `HttpClient` are _cold_, which is to say that they are _blueprints_ for making requests. Nothing will happen until you call `subscribe()`, and every such call will make a separate request. For example, this code sends a POST request with the same data twice:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
const req = http.post('/api/items/add', body);
|
||||
// 0 requests made - .subscribe() not called.
|
||||
req.subscribe();
|
||||
|
@ -230,7 +230,7 @@ Besides the URL and a possible request body, there are other aspects of an outgo
|
|||
|
||||
One common task is adding an `Authorization` header to outgoing requests. Here's how you do that:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
http
|
||||
.post('/api/items/add', body, {
|
||||
headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
|
||||
|
@ -244,7 +244,7 @@ The `HttpHeaders` class is immutable, so every `set()` returns a new instance an
|
|||
|
||||
Adding URL parameters works in the same way. To send a request with the `id` parameter set to `3`, you would do:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
http
|
||||
.post('/api/items/add', body, {
|
||||
params: new HttpParams().set('id', '3'),
|
||||
|
@ -269,7 +269,7 @@ before sending it to the server, and the interceptors can transform the response
|
|||
To implement an interceptor, you declare a class that implements `HttpInterceptor`, which
|
||||
has a single `intercept()` method. Here is a simple interceptor which does nothing but forward the request through without altering it:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
import {Injectable} from '@angular/core';
|
||||
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
|
||||
|
||||
|
@ -295,7 +295,7 @@ This pattern is similar to those in middleware frameworks such as Express.js.
|
|||
|
||||
Simply declaring the `NoopInterceptor` above doesn't cause your app to use it. You need to wire it up in your app module by providing it as an interceptor, as follows:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
import {NgModule} from '@angular/core';
|
||||
import {HTTP_INTERCEPTORS} from '@angular/common/http';
|
||||
|
||||
|
@ -338,7 +338,7 @@ If you have a need to mutate the request body, you need to copy the request body
|
|||
|
||||
Since requests are immutable, they cannot be modified directly. To mutate them, use `clone()`:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
||||
// This is a duplicate. It is exactly the same as the original.
|
||||
const dupReq = req.clone();
|
||||
|
@ -354,7 +354,7 @@ As you can see, the hash accepted by `clone()` allows you to mutate specific pro
|
|||
|
||||
A common use of interceptors is to set default headers on outgoing responses. For example, assuming you have an injectable `AuthService` which can provide an authentication token, here is how you would write an interceptor which adds it to all outgoing requests:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
import {Injectable} from '@angular/core';
|
||||
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
|
||||
|
||||
|
@ -375,7 +375,7 @@ export class AuthInterceptor implements HttpInterceptor {
|
|||
|
||||
The practice of cloning a request to set new headers is so common that there's actually a shortcut for it:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
const authReq = req.clone({setHeaders: {Authorization: authHeader}});
|
||||
```
|
||||
|
||||
|
@ -389,7 +389,7 @@ An interceptor that alters headers can be used for a number of different operati
|
|||
|
||||
Because interceptors can process the request and response _together_, they can do things like log or time requests. Consider this interceptor which uses `console.log` to show how long each request takes:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
import 'rxjs/add/operator/do';
|
||||
|
||||
export class TimingInterceptor implements HttpInterceptor {
|
||||
|
@ -414,7 +414,7 @@ Notice the RxJS `do()` operator—it adds a side effect to an Observable wit
|
|||
|
||||
You can also use interceptors to implement caching. For this example, assume that you've written an HTTP cache with a simple interface:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
abstract class HttpCache {
|
||||
/**
|
||||
* Returns a cached response, if any, or null if not present.
|
||||
|
@ -430,7 +430,7 @@ abstract class HttpCache {
|
|||
|
||||
An interceptor can apply this cache to outgoing requests.
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
@Injectable()
|
||||
export class CachingInterceptor implements HttpInterceptor {
|
||||
constructor(private cache: HttpCache) {}
|
||||
|
@ -467,7 +467,7 @@ Obviously this example glosses over request matching, cache invalidation, etc.,
|
|||
|
||||
To really demonstrate their flexibility, you can change the above example to return _two_ response events if the request exists in cache—the cached response first, and an updated network response later.
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
||||
// Still skip non-GET requests.
|
||||
if (req.method !== 'GET') {
|
||||
|
@ -507,7 +507,7 @@ Sometimes applications need to transfer large amounts of data, and those transfe
|
|||
|
||||
To make a request with progress events enabled, first create an instance of `HttpRequest` with the special `reportProgress` option set:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
const req = new HttpRequest('POST', '/upload/file', file, {
|
||||
reportProgress: true,
|
||||
});
|
||||
|
@ -518,7 +518,7 @@ change detection, so only turn them on if you intend to actually update the UI o
|
|||
|
||||
Next, make the request through the `request()` method of `HttpClient`. The result will be an Observable of events, just like with interceptors:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
http.request(req).subscribe(event => {
|
||||
// Via this API, you get access to the raw event stream.
|
||||
// Look for upload progress events.
|
||||
|
@ -553,7 +553,7 @@ In order to prevent collisions in environments where multiple Angular apps share
|
|||
|
||||
If your backend service uses different names for the XSRF token cookie or header, use `HttpClientXsrfModule.withOptions()` to override the defaults.
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
imports: [
|
||||
HttpClientModule,
|
||||
HttpClientXsrfModule.withOptions({
|
||||
|
@ -575,7 +575,7 @@ Angular's HTTP testing library is designed for a pattern of testing where the ap
|
|||
|
||||
To begin testing requests made through `HttpClient`, import `HttpClientTestingModule` and add it to your `TestBed` setup, like so:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
|
||||
import {HttpClientTestingModule} from '@angular/common/http/testing';
|
||||
|
||||
|
@ -595,7 +595,7 @@ That's it. Now requests made in the course of your tests will hit the testing ba
|
|||
|
||||
With the mock installed via the module, you can write a test that expects a GET Request to occur and provides a mock response. The following example does this by injecting both the `HttpClient` into the test and a class called `HttpTestingController`
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
it('expects a GET request', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {
|
||||
// Make an HTTP GET request, and expect that it return an object
|
||||
// of the form {name: 'Test Data'}.
|
||||
|
@ -624,7 +624,7 @@ it('expects a GET request', inject([HttpClient, HttpTestingController], (http: H
|
|||
|
||||
The last step, verifying that no requests remain outstanding, is common enough for you to move it into an `afterEach()` step:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) => {
|
||||
httpMock.verify();
|
||||
}));
|
||||
|
@ -634,7 +634,7 @@ afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) => {
|
|||
|
||||
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:
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
const req = httpMock.expectOne((req) => req.headers.has('Authorization'));
|
||||
```
|
||||
|
||||
|
@ -644,7 +644,7 @@ Just as with the `expectOne()` by URL in the test above, if 0 or 2+ requests mat
|
|||
|
||||
If you need to respond to duplicate requests in your test, use the `match()` API instead of `expectOne()`, which takes the same arguments but returns an array of matching requests. Once returned, these requests are removed from future matching and are your responsibility to verify and flush.
|
||||
|
||||
```javascript
|
||||
```typescript
|
||||
// Expect that 5 pings have been made and flush them.
|
||||
const reqs = httpMock.match('/ping');
|
||||
expect(reqs.length).toBe(5);
|
||||
|
|
Loading…
Reference in New Issue