【angular教程240112】09(完) Angular中的数据请求 与 路由

【angular教程240112】09(完) Angular中的数据请求 与 路由

目录标题

    • [一、 Angular 请求数据简介](#一、 Angular 请求数据简介)
      • [0 使用Angular内置模块HttpClientModule和HttpClientJsonpModule:](#0 使用Angular内置模块HttpClientModule和HttpClientJsonpModule:)
      • [1 Angular中的GET请求:](#1 Angular中的GET请求:)
      • [2 Angular中的POST请求:](#2 Angular中的POST请求:)
      • [3 Angular中的JSONP请求:](#3 Angular中的JSONP请求:)
      • 4使用Axios进行数据请求:
    • [二、 详解 Angular get 请求数据](#二、 详解 Angular get 请求数据)
      • [1 导入HttpClientModule:](#1 导入HttpClientModule:)
      • [2 使用HttpClient进行GET请求:](#2 使用HttpClient进行GET请求:)
      • [3 展示数据: 修改app.component.html文件](#3 展示数据: 修改app.component.html文件)
    • [三、 详解 Angular post 请求数据](#三、 详解 Angular post 请求数据)
      • [1 修改app.component.ts文件:](#1 修改app.component.ts文件:)
      • [2 修改app.component.html文件,添加一个按钮来触发POST请求:](#2 修改app.component.html文件,添加一个按钮来触发POST请求:)
    • [四. get传值&动态路由(routerLink进行传参跳转)](#四. get传值&动态路由(routerLink进行传参跳转))
      • [1.1 get传值](#1.1 get传值)
      • [1.2 动态路由](#1.2 动态路由)
    • [五 Angular中的路由 路由概述 配置路由 路由重定向 路由选中 默认路由 一、Angular创建一个默认带路由的项目、路由模块分析](#五 Angular中的路由 路由概述 配置路由 路由重定向 路由选中 默认路由 一、Angular创建一个默认带路由的项目、路由模块分析)
    • [六、 Angular中路由传值(get传值、动态路由)以及通过js跳转路由](#六、 Angular中路由传值(get传值、动态路由)以及通过js跳转路由)
    • [七 Angular路由的嵌套 父子路由](#七 Angular路由的嵌套 父子路由)

Angular中的数据请求 内置模块HttpClient实现(get post jsonp 以及第三方模板axios请求数据

一、 Angular get 请求数据

二、 Angular post提交数据

三、 Angular Jsonp请求数据

四、 Angular中使用第三方模块axios请求数据

五、Angular内置模块HttpClientModule HttpClientJsonpModule 的使用

一、 Angular 请求数据简介

当然,了解如何在Angular中使用不同的方法来请求数据。首先,需要了解Angular中的HttpClient模块,它是用于发送网络请求的主要方式。然后,将展示如何使用axios,这是一个流行的第三方库,用于发送HTTP请求。

0 使用Angular内置模块HttpClientModule和HttpClientJsonpModule:

这些模块是Angular提供的,用于在应用中进行HTTP通信。需要在的Angular模块中导入它,才能在服务或组件中使用HttpClient。

typescript 复制代码
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule,
    HttpClientJsonpModule
    // other imports
  ],
  // declarations and bootstrap
})
export class AppModule { }

1 Angular中的GET请求:

在Angular中,可以使用HttpClient模块来执行GET请求。这通常用于从服务器检索数据。

typescript 复制代码
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

getData() {
  this.http.get('YOUR_API_URL').subscribe(data => {
    console.log(data);
  });
}

2 Angular中的POST请求:

POST请求通常用于向服务器发送数据。在Angular中,可以这样做:

typescript 复制代码
postData() {
  this.http.post('YOUR_API_URL', {yourDataObject}).subscribe(data => {
    console.log(data);
  });
}

3 Angular中的JSONP请求:

JSONP用于跨域请求。在Angular中,可以使用HttpClientJsonpModule和HttpClient来发送JSONP请求。

typescript 复制代码
jsonpRequest() {
  this.http.jsonp('YOUR_JSONP_API_URL', 'callback').subscribe(data => {
    console.log(data);
  });
}

4使用Axios进行数据请求:

axios是一个第三方库,可以在Angular项目中使用它来发送HTTP请求。

typescript 复制代码
import axios from 'axios';

axiosGet() {
  axios.get('YOUR_API_URL').then(response => {
    console.log(response.data);
  });
}

axiosPost() {
  axios.post('YOUR_API_URL', {yourDataObject}).then(response => {
    console.log(response.data);
  });
}

二、 详解 Angular get 请求数据

在Angular中进行数据请求前,需要理解HttpClientModule。这是一个Angular模块,用于提供发送HTTP请求的方法。首先,需要在的应用模块中导入它。

1 导入HttpClientModule:

打开的Angular项目中的app.module.ts文件,然后添加以下内容:

typescript 复制代码
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http'; // 添加这行
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule // 添加这行
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2 使用HttpClient进行GET请求:

打开app.component.ts文件,添加以下内容:

typescript 复制代码
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-angular-app';
  data: any;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(data => {
      this.data = data;
    });
  }
}

这段代码在组件初始化时发送GET请求到一个测试API,并将响应数据存储在data属性中。

3 展示数据: 修改app.component.html文件

添加以下内容以展示数据:

html 复制代码
<div>
  <h1>Welcome to {{ title }}!</h1>
  <pre>{{ data | json }}</pre>
</div>

这将在页面上显示从API请求获得的数据。

4 子组件 app-news

展示

html 复制代码
<button  (click)="getData()">get请求数据</button>
<ol>
    <li  *ngFor="let item of list">
       - {{item.title}}
    </li>
</ol>

请求

ts 复制代码
 import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.scss'],
})
export class NewsComponent implements OnInit {
  constructor(public http: HttpClient) {}
  ngOnInit(): void {}
    
 

  public list: any[] = [];
  getData() {
    //服务器必须允许跨域
    // let api = 'https://jsonplaceholder.typicode.com/posts';
    let api = 'http://a.itying.com/api/productlist';
    this.http.get(api).subscribe((response: any) => {
      console.log(response);
      this.list = response.result;
    });
  }

}

三、 详解 Angular post 请求数据

介绍了如何设置Angular项目和使用HttpClient模块进行GET请求。现在,看看如何使用这个模块来执行POST请求。

Angular中的POST请求

POST请求通常用于将数据发送到服务器。例如,可能想要提交表单数据或发送JSON对象到后端API。

理解POST请求:

POST请求用于将数据发送到服务器,例如,当提交一个表单时。

在Angular中,可以使用HttpClient的post方法来执行POST请求。

实现POST请求:

首先,确保已经按照之前的指导在的Angular项目中导入了HttpClientModule并注入了HttpClient。

接下来,将使用HttpClient的post方法来发送一个请求。

示例代码:

假设想要向一个URL发送一些数据,如下所示是在Angular组件中实现的示例代码。

1 修改app.component.ts文件:

typescript 复制代码
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-angular-app';
  
  constructor(private http: HttpClient) {}

  postData() {
    const url = 'YOUR_API_ENDPOINT'; // 替换为的API端点
    const data = { name: 'John', age: 30 }; // 这里是想发送的数据

    this.http.post(url, data).subscribe(response => {
      console.log(response);
      // 这里处理响应数据
    }, error => {
      console.error(error);
      // 这里处理错误情况
    });
  }
}

2 修改app.component.html文件,添加一个按钮来触发POST请求:

html 复制代码
<div>
  <h1>Welcome to {{ title }}!</h1>
  <button (click)="postData()">Send POST Request</button>
</div>

注意事项:

确保使用的URL和数据格式与的后端API兼容。

subscribe方法用于处理异步响应。第一个函数处理成功的响应,第二个函数处理错误。

测试:

运行的Angular应用并点击按钮,的应用会向指定的URL发送POST请求。

可以在浏览器的开发者工具中查看网络活动,以确认请求是否成功发送。

通过这个例子,应该能够开始在Angular中使用POST请求了。当熟悉了基础概念之后,可以开始探索更复杂的用例,例如发送表单数据、处理不同类型的响应等。

四. get传值&动态路由(routerLink进行传参跳转)

1.1 get传值

1.1.1 get传值

在一个组件的html文件传递数据

html 复制代码
<li *ngFor="let item of list;let key=index;">
      <a [routerLink]="['/newscontent']" [queryParams]="{aid:key}">{{key}}--{{item}}</a>
    </li>

1.1.2 接收

在另外一个组件的ts文件接收数据

ts 复制代码
   import { ActivatedRoute } from '@angular/router';
   constructor(public route:ActivatedRoute) { }
   this.route.queryParams.subscribe((data)=>{
        console.log(data);
   })

1.2 动态路由

1.2.1 配置动态路由

app-routing.module.ts

ts 复制代码
       {
        path:'newscontent/:aid',component:NewscontentComponent
      }

1.2.2 跳转

在一个组件的html文件传递数据

html 复制代码
        <ul>
        <li *ngFor="let item of list;let key=index;">
			<!--  key 就是待会传递的数据 他的名称是aid -->
          <a [routerLink]="[ '/newscontent/', key ]">{{key}}---{{item}}</a>
        </li>
      </ul>

1.2.3 接收

在另外一个组件的ts文件接收数据

ts 复制代码
       import { ActivatedRoute } from '@angular/router';
        constructor(public route:ActivatedRoute) { }
        this.route.params.subscribe((data)=>{
              console.log(data);
        })

五 Angular中的路由 路由概述 配置路由 路由重定向 路由选中 默认路由 一、Angular创建一个默认带路由的项目、路由模块分析

二、Angular 配置路由、 默认路由
三、Angular  routerLink跳转页面      
四、Angular routerLinkActive设置routerLink默认选中路由    

在Angular中,路由是一种导航方法,它允许用户在不同的视图之间导航。这是一个单页应用(SPA)的核心特性。将逐步介绍如何在Angular中设置和使用路由。

一、Angular创建带路由的项目及路由模块分析

1创建带路由的Angular项目:

当使用Angular CLI创建新项目时,可以选择包含路由功能。使用以下命令创建新项目并包含路由支持:

sql 复制代码
ng new my-angular-app --routing

这将创建一个新的Angular项目my-angular-app,并在其中包含路由功能。

2路由模块分析:

在创建的项目中,会发现app-routing.module.ts文件。这是Angular中的路由模块,用于配置和管理路由。基本结构如下:

typescript 复制代码
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  // 这里配置路由
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

二、Angular配置路由及默认路由

1配置路由:

在app-routing.module.ts文件中,可以定义路由数组。每个路由都是一个对象,至少包含两个属性:path和component。

typescript 复制代码
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent }
  // 其他路由...
];
2默认路由:

默认路由是当没有任何其他路由匹配时应用的路由。通常,会设置一个指向首页或者404页面的默认路由。

typescript 复制代码
{ path: '', redirectTo: '/home', pathMatch: 'full' }

三、Angular routerLink跳转页面

routerLink是Angular的一个指令,用于在应用内部进行导航。例如,在的组件模板中:

html 复制代码
<nav>
  <a routerLink="/home">Home</a>
  <a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
<router-outlet>是放置路由内容的占位符。

四、Angular routerLinkActive设置默认选中路由

routerLinkActive是一个指令,用于自动为活动的路由链接添加CSS类。

html 复制代码
<nav>
  <a routerLink="/home" routerLinkActive="active">Home</a>
  <a routerLink="/about" routerLinkActive="active">About</a>
</nav>

在这个例子中,当路由激活时,相应的链接将具有active类。可以在CSS中定义.active样式,以指示哪个链接是当前激活的。

这些步骤概述了在Angular中设置和使用路由的基础知识。实际应用中,路由可能会更加复杂,包括嵌套路由、路由守卫(用于权限控制)等。但这些基础概念是开始使用Angular路由的基础。

六、 Angular中路由传值(get传值、动态路由)以及通过js跳转路由

一、Angular中get传值 以及获取get传值
二、Angular 中动态路由 以及获取动态路由的值
三、Angular 动态路由 js跳转路由
四、Angular get传值 js跳转路由

在Angular中,路由传值是一种重要的技术,它允许在不同组件之间传递信息。以下是关于如何实现GET传值、动态路由传值,以及如何通过JavaScript代码来跳转路由的详细指导。

一、Angular中GET传值及获取GET传值

GET传值:

在Angular中,GET传值通常是指通过查询参数(query parameters)来传递值。例如,可能有一个URL类似于/product?id=123。

要在路由链接中添加查询参数,可以使用[queryParams]绑定。

html 复制代码
<a [routerLink]="['/product']" [queryParams]="{id: 123}">Product</a>

获取GET传值:

在目标组件中,可以使用ActivatedRoute服务来获取这些查询参数。

首先,需要在的组件中注入ActivatedRoute。

typescript 复制代码
import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.queryParams.subscribe(params => {
    console.log('Product ID:', params['id']);
  });
}

二、Angular中动态路由及获取动态路由的值

动态路由:

动态路由是指路由路径中包含一些动态变化的部分,如/product/123。

在定义路由时,使用冒号(:)来指定动态部分。

typescript 复制代码
{ path: 'product/:id', component: ProductComponent }

```获取动态路由的值:
同样地,可以使用ActivatedRoute服务获取动态参数的值。
```typescript

ngOnInit() {
  this.route.params.subscribe(params => {
    console.log('Product ID:', params['id']);
  });
}

三、Angular动态路由JavaScript跳转路由

要通过JavaScript代码跳转路由,可以使用Angular的Router服务。

typescript 复制代码
import { Router } from '@angular/router';

constructor(private router: Router) {}

navigateToProduct(id: number) {
  this.router.navigate(['/product', id]);
}

这个方法将会导航到像/product/123这样的动态路由。

四、Angular GET传值JavaScript跳转路由

通过JavaScript代码进行带有GET参数的路由跳转也是可能的。

typescript 复制代码
navigateWithQueryParams() {
  this.router.navigate(['/product'], { queryParams: { id: 123 } });
}

这将会导航到带有查询参数的路由,例如/product?id=123。

总结

GET传值是使用查询参数在路由间传递数据的方法。

动态路由允许在URL的一部分中传递变量值。

使用Router服务可以通过JavaScript代码进行路由跳转,无论是到动态路由还是带有查询参数的路由。

这些概念是Angular路由的核心部分,理解和掌握它们将对构建复杂的Angular应用至关重要。

七 Angular路由的嵌套 父子路由

一、Angular路由的嵌套的用途
二、Angular 中配置使用嵌套路由 

在Angular中,嵌套路由(也称为子路由)是一种强大的功能,它允许在应用中创建更丰富的页面层次结构。下面将详细介绍嵌套路由的用途和配置方法。

一、Angular路由的嵌套的用途

嵌套路由主要用于以下情况:

创建更复杂的UI结构:

在单页应用(SPA)中,不同的视图组件可以嵌套在一起,形成多层次的用户界面。通过使用嵌套路由,可以在父路由下组织子视图,使结构更加清晰。

模块化路由管理:

对于大型应用,嵌套路由有助于将路由逻辑分解到不同的模块中,使代码更加模块化和可管理。

保持UI状态:

在某些情况下,可能希望保留父视图的状态(如导航菜单或页眉),同时更改子视图。嵌套路由使得这成为可能。

二、Angular中配置使用嵌套路由

1 配置父路由:

嵌套路由的配置开始于定义一个父路由。父路由通常会有一个path和一个component,还有一个children数组定义子路由。

typescript 复制代码
const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
    children: [
      // 子路由在这里定义
    ]
  }
];
2 定义子路由:

在children数组中,可以定义任意数量的子路由。每个子路由也有自己的path和component。

typescript 复制代码
children: [
  { path: 'child1', component: Child1Component },
  { path: 'child2', component: Child2Component }
]

使用展示子视图:

在父组件的模板中,使用标签来指定子视图的展示位置。

html 复制代码
<!-- ParentComponent的模板 -->
<h1>父组件</h1>
<router-outlet></router-outlet> <!-- 子视图将在这里渲染 -->
导航到嵌套路由:
使用routerLink进行导航时,路径应该相对于父路由。
html

<a [routerLink]="['/parent/child1']">Child 1</a>
<a [routerLink]="['/parent/child2']">Child 2</a>

完整示例:

假设有ParentComponent、Child1Component和Child2Component,上述代码展示了如何设置它们之间的嵌套路由。

通过嵌套路由,可以构建更为复杂和功能丰富的应用界面。它是Angular强大的路由功能之一,可以帮助有效地管理大型应用的路由结构。在实际应用中测试的路由配置,才能确保按预期工作。

相关推荐
云草桑6 分钟前
逆向工程 反编译 C# net core
前端·c#·反编译·逆向工程
布丁椰奶冻12 分钟前
解决使用nvm管理node版本时提示npm下载失败的问题
前端·npm·node.js
Leyla37 分钟前
【代码重构】好的重构与坏的重构
前端
影子落人间41 分钟前
已解决npm ERR! request to https://registry.npm.taobao.org/@vant%2farea-data failed
前端·npm·node.js
世俗ˊ1 小时前
CSS入门笔记
前端·css·笔记
子非鱼9211 小时前
【前端】ES6:Set与Map
前端·javascript·es6
6230_1 小时前
git使用“保姆级”教程1——简介及配置项设置
前端·git·学习·html·web3·学习方法·改行学it
想退休的搬砖人1 小时前
vue选项式写法项目案例(购物车)
前端·javascript·vue.js
加勒比海涛2 小时前
HTML 揭秘:HTML 编码快速入门
前端·html
啥子花道2 小时前
Vue3.4 中 v-model 双向数据绑定新玩法详解
前端·javascript·vue.js