Father-child component value transmission

@input () and @Output() provide a way for child components to communicate with their parents. @input () allows the parent component to update data in the child component. In contrast, @output () allows a child component to send data to its parent.

The parent component passes a value – @input to the child component

The @input () decorator in a child component or directive indicates that the property can get a value from its parent component.

The parent component app.com ponent. Ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root'.templateUrl: './app.component.html'.styleUrls: ['./app.component.scss']})export class AppComponent {
  title = 'my-app';
  msg = 'Hello sub component';
}
Copy the code

The parent component app.com ponent. HTML

<! --The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<app-child [item] ="msg"></app-child>

<router-outlet></router-outlet>

Copy the code

Subcomponents child.com ponent. Ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child'.templateUrl: './child.component.html'.styleUrls: ['./child.component.scss']})export class ChildComponent implements OnInit {
  // The @input () decorator in a child component or directive indicates that the property can get a value from its parent component.
  @Input() item: string;
  
  constructor(){}ngOnInit(){}}Copy the code

Subcomponents child.com ponent. HTML

<p>Values from parent to child: {{item}}</p>
Copy the code

The child component passes values to the parent – @Output, EventEmitter

The @output () decorator in a child or directive allows data to be passed from the child to the parent. The child uses the @output () attribute to raise an event to notify the parent of the change. To emit events, @Output() must be of type EventEmitter, which is the class in @Angular /core that emits custom events.

Subcomponents child.com ponent. Ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child'.templateUrl: './child.component.html'.styleUrls: ['./child.component.scss']})export class ChildComponent implements OnInit {
  // The @input () decorator in a child component or directive indicates that the property can get a value from its parent component.
  @Input() item: string;
  // The @output () decorator in a child or directive allows data to be passed from the child to the parent.
  @Output() newItemEvent = new EventEmitter<string> ();constructor(){}ngOnInit(){}addNewItem(value: string) {
    console.log(value);
    this.newItemEvent.emit(value); }}Copy the code

Subcomponents child.com ponent. HTML

<p>Values from parent to child: {{item}}</p>
<label>Add an item: <input #newItem></label>
<button (click) ="addNewItem(newItem.value)">Child component adds item to parent component</button>
Copy the code

The parent component app.com ponent. Ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root'.templateUrl: './app.component.html'.styleUrls: ['./app.component.scss']})export class AppComponent {
  title = 'my-app';
  msg = 'Hello sub component';
  items = ['item1'.'item2'.'item3'.'item4'];
  addItem(newItem: string) {
    this.items.push(newItem); }}Copy the code

The parent component app.com ponent. HTML

<! --The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<ul>
  <li *ngFor="let item of items">{{item}}</li>
</ul>
<app-child [item] ="msg" (newItemEvent) ="addItem($event)"></app-child>

<router-outlet></router-outlet>

Copy the code

2. Routing

Routing is used in the project

To use routing in a project, first create an application project with routing. An item with a route can be created with the command ng new routing-app –routing.

1. Add components to the route

To use the Angular router, an application must have at least two components to navigate from one to the other. To create a component using the CLI, type the following on the command line, where first is the name of the component:

ng generate component first
Copy the code

Repeat this step for the second component, but give it a different name. The new name here is Second.

ng generate component second
Copy the code

The CLI automatically adds the Component suffix, so if you’re writing a first-Component, the Component name is FirstComponentComponent.

2. Import these new components

To use these new components, import them into the AppRoutingModule at the top of the file as follows:

// In app-routing.module.ts
import { FirstComponent } from './first/first.component';
import { SecondComponent } from './second/second.component';
Copy the code

3. Define a basic route

There are three basic building blocks for creating a route. Import the AppRoutingModule into the AppModule and add it to the Imports array. The Angular CLI does this for you. However, if you are manually creating an application or using an existing non-CLI application, verify that the import and configuration are correct.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module'; // CLI imports AppRoutingModule
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule // CLI adds AppRoutingModule to the AppModule's imports array].providers: [].bootstrap: [AppComponent]
})
export class AppModule {}Copy the code

Import RouterModule and Routes into your routing module. The Angular CLI does this automatically. The CLI also sets up an array of Routes for your Routes and an array of imports and exports for @NgModule().

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'; // CLI imports router

const routes: Routes = []; // sets up routes constant where you define your routes

// configures NgModule imports and exports
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}Copy the code

2. Define your route in the Routes array. Each route in this array is a JavaScript object with two properties. The first attribute, PATH, defines the URL path for the route. The second component property defines the component that Angular uses as its path.

const routes: Routes = [
  { path: 'first-component'.component: FirstComponent },
  { path: 'second-component'.component: SecondComponent },
];
Copy the code

3. Finally add these routes to your application. Now that you have defined routes, you can add them to your application. First, add links to both components. Assign the link to which the route is to be added to the routerLink property. Set the value of the property to this component so that the value is displayed when the user clicks on individual links. Next, modify the component template to include the

tag. This element notifies Angular that you can update the app view with the routed component selected.

<! --app.component.html-->

<h1>Angular Router App</h1>
<! -- This nav gives you links to click, which tells the router which route to use (defined in the routes constant in AppRoutingModule) -->
<nav>
  <ul>
    <li><a routerLink="/first-component" routerLinkActive="active">First Component</a></li>
    <li><a routerLink="/second-component" routerLinkActive="active">Second Component</a></li>
  </ul>
</nav>
<! -- The routed views render in the <router-outlet>-->
<router-outlet></router-outlet>
Copy the code

Routing order

The order of the routes is important because the Router uses a “first come, first served” policy when matching routes, so a more specific route should be placed in front of a less specific route. Routes to static paths are listed first, followed by an empty path route that matches the default route. The wildcard route is the last one, because it matches every URL and is selected by the Router only if none of the other routes match.

Set the wildcard route

Attempts by users to navigate to non-existent application parts should be handled well in normal applications. To add this feature to your application, you need to set up wildcard routing. The Angular router selects this route when the requested URL does not match any router path.

To set up wildcard routes, add the following code to the Routes definition.

{ path: '* *'.component: PageNotFoundComponent }
Copy the code

Setting redirection

To set the redirect, configure the route with the path of the redirect source, the Component to redirect the target, and a pathMatch value to tell the router how to match the URL.

const routes: Routes = [
  { path: 'first-component'.component: FirstComponent },
  { path: 'second-component'.component: SecondComponent },
  { path: ' '.redirectTo: '/first-component'.pathMatch: 'full' }, // redirect to `first-component`
  { path: '* *'.component: PageNotFoundComponent },  // Wildcard route for a 404 page
];
Copy the code

Routing and the cords

1. Dynamic routing

1. Configure dynamic routes in the Routes array in the app-routing.module.ts file

{
    path: 'first-component/:id'.component: FirstComponent,
}
Copy the code

2. Jump to and pass values in THE HTML page

<! -- Dynamic routing -->
<a routerLink="/first-component/3" routerLinkActive="active">First Component</a>
<! - or - >
<a [routerLink] ="['/first-component/',3]">First Component</a>
Copy the code

2. Pass the parameter as query

Pass the parameter directly to the A tag of the routerLink in the HTML page

<a routerLink="/second-component" [queryParams] ="{name: 'xiaoxiao Xiaoxiao Xiaohong '}" routerLinkActive="active">
  Second Component
</a>
Copy the code

Obtain route parameter information

1. Obtain the value of the dynamic route

If I want to get the value of the dynamic route in the FirstComponent, step 1: Import the ActivatedRoute module in the first.component.ts file and inject it as a route into the constructor function.

import {Component, OnInit} from '@angular/core';

import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-first'.templateUrl: './first.component.html'.styleUrls: ['./first.component.scss']})export class FirstComponent implements OnInit {
  constructor(private route: ActivatedRoute){}}Copy the code

We can then get the value passed by using the route.params.subscribe() method.

ngOnInit() {
    // Get the dynamic routing value
    console.log(this.route.params);
    this.route.params.subscribe(data= > {
      console.log(data);
      this.id = data.id
    })
  }
Copy the code

2. Get the parameters passed in the query form

If I want to get the value passed in query form in SecondComponent, step 1: Import the ActivatedRoute module in second.component.ts and inject it as a route into the constructor function.

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-second'.templateUrl: './second.component.html'.styleUrls: ['./second.component.scss']})export class SecondComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
  ){}}Copy the code

Then you can through the route. The queryParams. The subscribe () method to obtain the transfer of value.

ngOnInit() {
    // Get the params pass
    this.route.queryParams.subscribe(params= > {
      console.log(params);
      this.name = params['name'];
    });
  }
Copy the code

Js jump Route (programmatic navigation)

I’m going to demonstrate programmatic navigation in the AppComponent, so I’ll first introduce the Router module in app.component.ts and initialize it in the constructor function. The NavigationExtras module is introduced for query argument passing. The NavigationExtras module does not need to be initialized in the constructor constructor function.

import { Router, NavigationExtras } from '@angular/router'

constructor(private router: Router) {}
Copy the code

1. Js redirects to common routes

Start by defining a button on the page to simulate a jump

<button (click) ="goHome()">Js jump route</button>
Copy the code

To jump, use the router.navigate() method

// js redirects to common routes
goHome() {
  this.router.navigate(['/home'])}Copy the code

2. Js jump dynamic routing

<! -- js dynamic route jump -->
<button (click) ="goToPath()">Js Dynamic route redirect</button>
Copy the code

To jump, use the router.navigate() method

// redirect dynamic routing
goToPath() {
  // Route hop is suitable for both common and dynamic routes
  this.router.navigate(['/first-component/'.'123'])}Copy the code

3, js jump route query form to pass the parameter

Note: The NavigationExtras module needs to be introduced

<button (click) ="queryRoute()">Js Redirects the route query</button>
Copy the code

To jump, use the router.navigate() method

// js jump route query pass parameter (get pass value)
queryRoute() {
    let queryParams: NavigationExtras = {
      queryParams: {
        name: Honor of Kings}}this.router.navigate(['/second-component'], queryParams);
}
Copy the code

Embedded routines by

As your application becomes more complex, you may want to create relative routes outside of the root component. These nested routines are called child routes by type. This means you need to add a second to your app because it’s another

in addition to the AppComponent.

In this example, there are also two child components, child-a and child-b. The FirstComponent here has its own

<h2>First Component</h2>

<nav>
  <ul>
    <li><a routerLink="child-a">Child A</a></li>
    <li><a routerLink="child-b">Child B</a></li>
  </ul>
</nav>

<router-outlet></router-outlet>
Copy the code

Child routes, like other routes, require both path and Component. The only difference is that you put the child route in the children array of the parent route.

const routes: Routes = [
  {
    path: 'first-component'.component: FirstComponent, // this is the component with the <router-outlet> in the template
    children: [{path: 'child-a'.// child route path
        component: ChildAComponent, // child route component that the router renders
      },
      {
        path: 'child-b'.component: ChildBComponent, // another child route component that the router renders},],},];Copy the code

HTTP client

Use HTTP to communicate with back-end services. Most front-end applications need to communicate with the server over HTTP to download or upload data and access other back-end services. Angular provides applications with a simplified HTTP client API, the HttpClient service class in @angular/common/ HTTP.

The HTTP client service provides the following main functions.

  • The ability to request typed response objects.

  • Simplified error handling.

  • Testability of various features.

  • Request and response interception mechanisms.

Preparation of server communication

To use HttpClient, import the Angular HttpClientModule in app.module.ts. Most applications import it in the root AppModule.

// app/app.module.ts
  
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
Copy the code

2. Introduce HttpClient where needed and declare it in the constructor function. (I’m going to use it in NewsComponent, so import HttpClient in news.component.ts and declare it in constructor function)

// news.component.ts
  
import {HttpClient} from "@angular/common/http";
  
constructor(public http:HttpClient){}Copy the code

Get request data

1. Define a button in the news.component.html file to implement the GET method to request server data.

<button (click) ="getData()">A get request</button>
Copy the code

2. Implement the getData() method in the news.component.ts file. The get request interface can use the open source HTTPS :httpbin.org/get

/ / get request
  getData() {
    // https:httpbin.org/get
    // https://httpbin.org/post
    let api = 'http://a.itying.com/api/productlist';
    this.http.get(api).subscribe((res: any) = > {
      console.log(res);
      this.list = res.result; })}Copy the code

Post submit data

Angular5.x uses the HttpClientModule for get, POST, and server interactions.

Import HttpClientModule in app.module.ts and inject it

import {HttpClientModule} from '@angular/common/http';
  
imports: [ BrowserModule, HttpClientModule ]
Copy the code

2. Introduce the HttpClient/HttpHeaders module where needed and declare HttpClient in the constructor function.

Define a button in the news.component.html file to implement a POST request for server data.

<button (click) ="doLogin()">Post submit data</button>
Copy the code

2. Implement the doLogin() method in news.component.ts. The post request interface can use the open source HTTPS :httpbin.org/post.

/ / post request
  doLogin() {
    const httpOptions = {
      headers: new HttpHeaders({"content-type": 'application/json'})};let url = 'https://httpbin.org/post';
    this.http.post(url, {name: 'Little smile left a rainbow'.age: 18}, httpOptions).subscribe((res: any) = > {
      console.log(res);
      this.postDate = res.json; })}Copy the code

Jsonp requests data

Import HttpClientModule and HttpClientJsonpModule into app.module.ts.

import {HttpClientModule,HttpClientJsonpModule} from '@angular/common/http';
  
imports: [ BrowserModule, HttpClientModule, HttpClientJsonpModule ]
Copy the code

2. Introduce HttpClient where needed and declare it in the constructor.

// news.component.ts
  
import {HttpClient} from "@angular/common/http";
constructor(public http:HttpClient){}Copy the code
<button (click) ="getJsonp()">Jsonp handles cross domains</button>
Copy the code
// jSONp cross-domain request
  getJsonp() {
    /* * http://a.itying.com/api/productlist?callback=xxx * http://a.itying.com/api/productlist?cb=xxx * */
    let api = 'http://a.itying.com/api/productlist';
    this.http.jsonp(api, 'callback').subscribe((res: any) = > {
      console.log(res);
      this.list = res.result; })}Copy the code

Angular uses the third-party module AXIos to request data

1. Install AxiOS

npm install axios --save
Copy the code

2. Introduce Axios where it’s used

import axios from 'axios';
Copy the code

3. Read the AXIos documentation to use

axios.get('/user? ID=12345') 
  .then(function (response){ 
  // handle success console.log(response); 
  }).catch(function (error) {
  // handle error console.log(error); 
  }).then(function () { 
  // always executed 
  });
Copy the code

Next, we create an HttpService to use Axios, where we can wrap axios a bit.

// service/http-service.service.ts
  
import {Injectable} from '@angular/core';

import axios from 'axios';

@Injectable({
  providedIn: 'root'
})
export class HttpServiceService {

  constructor(){}axiosGet(api) {
    return new Promise((resolve, reject) = > {
      axios.get(api)
        .then(res= >{ resolve(res); }}})})Copy the code

We then import the HttpServiceService service in app.module.ts and inject it into the providers array.

// app.module.ts
  
// Import services
import {HttpServiceService} from './service/http-service.service';
  
// Inject the service
providers: [HttpServiceService],
Copy the code

Then use the HttpServiceService service in the NewsComponent

// news.component.ts
  
// Import services
import {HttpServiceService} from '.. /service/http-service.service'

/ / initialization
constructor(public httpService: HttpServiceService) {}
Copy the code
<! --news.component.html-->
<button (click) ="axiosGetData()">Get the data through Axios</button>
Copy the code
// news.component.ts
  
// the axios get method gets the data
  axiosGetData() {
    let api = 'http://a.itying.com/api/productlist';
    this.httpService.axiosGet(api).then((res: any) = > {
      console.log(res);
      this.list = res.data.result; })}Copy the code