参照 草根专栏- ASP.NET Core + Ng6 实战: https://v.qq.com/x/page/a0769armuui.html

1、environment.ts 添加apiUrlBase(资源访问Api地址):

export const environment = {
production: false ,
apiUrlBase: 'https://localhost:6001/api'
};

2、添加父类service:

ng g s shared/base

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment'; @Injectable({
providedIn: 'root'
})
export class BaseService { apiUrlBase = environment.apiUrlBase; constructor() { }
}

3、添加 Post service

ng g s blog/services/post

4、blog.module.ts 引用 service

  providers: [
PostService
]

5、ng g c blog/components/post-list

6、添加二层路由: sidenav.component.html

  <div class="app-sidenav-content">
<app-toolbar (toggleSidenav)="drawer.toggle()"></app-toolbar>
<router-outlet></router-outlet>
</div>

7、注册二层子路由

const routes: Routes = [
{
path: '', component: BlogAppComponent,
children : [
{path: 'post-list' , component: PostListComponent },
{path: '**' , redirectTo: 'post-list' }
]
} ];

8、service获取数据:

9、跨域配置

        public void ConfigureServices(IServiceCollection services)
{ //配置跨域
services.AddCors(options =>
{
options.AddPolicy("AllowAngularDevOrigin",
builder => builder.WithOrigins("http://localhost:4200")
.WithExposedHeaders("X-Pagination")
.AllowAnyHeader()
.AllowAnyMethod());
}); services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAngularDevOrigin"));//跨域配置
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
{ app.UseCors("AllowAngularDevOrigin");//跨域配置 }

10、建立   proxy.conf.js  配置

const PROXY_CONFIG = [
{
context: [
"/api"
],
target: "http://localhost:3000",
secure: false
}
] module.exports = PROXY_CONFIG;

11、angular.json中配置:

        "proxyConfig": "src/proxy.conf.js"

12、获取api header数据:

  getPosts() {
this.postService.getPagedPosts(this.postParameter).subscribe(resp => {
this.pageMeta = JSON.parse(resp.headers.get('X-Pagination')) as PageMeta;
});
}

13、获取body数据:

建立entity.ts    post.ts   link.ts      result-with-links      page-meta.ts   接受body传输的数据:

14、post-list.component.ts 中解析

@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.scss']
})
export class PostListComponent implements OnInit { postParameter = new PostParameters({ orderBy: 'id desc', pageSize: , pageIndex: });
posts: Post[];
pageMeta: PageMeta;
constructor(private postService: PostService) { } ngOnInit() {
this.getPosts();
} getPosts() {
this.postService.getPagedPosts(this.postParameter).subscribe(resp => {
this.pageMeta = JSON.parse(resp.headers.get('X-Pagination')) as PageMeta;
const result = {...resp.body} as ResultWithLinks<Post>;
this.posts = result.value;
});
} }

15、post-list.component.html显示数据

<div *ngIf="!pageMeta">
<mat-spinner></mat-spinner>
</div>
<div *ngIf="pageMeta">
<ng-container *ngFor="let item of posts">
{{item.title}}
</ng-container> </div>

Angualr6访问API的更多相关文章

  1. IdnentiyServer-使用客户端凭据访问API

    情景如下:一个客户端要访问一个api,不需要用户登录,但是又不想直接暴露api给外部使用,这时可以使用identityserver添加访问权限. 客户端通过clientid和secrect访问iden ...

  2. Vue.js Cookbook: 添加实例属性; 👍 axios(4万➕✨)访问API; filters过滤器;

    add instance properties //加上$,防止和已经定义的data,method, computed的名字重复,导致被覆写.//可以自定义添加其他符号. Vue.prototype. ...

  3. vue中比较完美请求的栗子(使用 axios 访问 API)

    vue中比较完美请求的栗子(使用 axios 访问 API) 官网地址:https://vuejs.bootcss.com/v2/cookbook/using-axios-to-consume-api ...

  4. 访问API的方式为:localhost/api/customers, 创建自定义JSON格式化器

    注意的是,访问API的方式为:localhost/api/customers,在实际中将要根据情况替换合适的端口,默认所有的WEB API都是通过/api根目录的方式访问的 创建自定义JSON格式化器 ...

  5. 五、通过密码访问API

    通过密码访问API 一.客户端 图: 客户端请求代码: static void Main(string[] args) { Console.WriteLine("确定三个项目都已经启动&qu ...

  6. c#后台代码请求访问api接口

    前言:最近公司项目与外部api接口对接较多 ,写下自己的代码总结.介绍两种访问方式(HttpClient.HttpWebRequest) 一.HttpWebRequest 访问Api private ...

  7. Identity Server 4资源拥有者密码认证控制访问API

    基于上一篇文章中的代码进行继续延伸,只需要小小的改动即可,不明白的地方可以先看看本人上一篇文章及源码: Identity Server 4客户端认证控制访问API 一.QuickStartIdenti ...

  8. swagger访问api, TypeError: Failed to fetch

    用swagger访问https://localhost:44360/api/ads/1, 得到的结果是 TypeError: Failed to fetch.一开始以为是后端代码问题,检查了好久,才发 ...

  9. Tomcat 配置 项目 到tomcat目录外面 和 域名绑定访问(api接口、前端网站、后台管理网站)

    先停止tomcat服务 1.进入apache-tomcat-7.0.68/conf/Catalina/localhost(如果之前还都没有启动过tomcat,是不会有此目录的,先启动一次再关闭,会自动 ...

随机推荐

  1. ES5 实现 ES6 的 class以及extends

    ts中是这样的 class Greeter { greeting:string; constructor(message:string){ this.greeting = message; } gre ...

  2. MySQL学习之视图的使用

    视图基本操作 创建视图 视图的本质就是SQL指令(select语句) 基本语法:create view 视图名 as  select 指令; 在这里的select指令可以是单表数据,也可以是连接查询. ...

  3. windows下labelme的安装

    1.安装Anaconda 2.进入Anaconda文件夹下 3.输入conda create --name=labelme python=3.5 4.输入activate labelme 然后建立的l ...

  4. JSP/Servlet开发——第十一章 Ajax交互扩展

    1. jQuery实现Ajax的方法: ●除了$.ajax()方法以外,jQuery还提供了其他多种更简单的 Ajax 实现方法,如$.get().$.post().$.getJSON().对象.lo ...

  5. Git-2.15.1.2-64-bit安装

    方法/步骤    我们在百度搜索git,然后在git的官网上找到git的下载页面,如下图所示.在首页在Downloads处选择下载Windows版本,当然您可以根据需求下载其他版本的安装文件.     ...

  6. php 批量去除项目文件bom头

    <?php if (isset($_GET['dir'])) { //设置文件目录 $basedir = $_GET['dir']; } else { $basedir = '.'; } $au ...

  7. yii学习笔记(6),数据库操作(增删改)

    数据库增删改操作通过活动记录实例来完成 插入记录 /* ----------添加记录---------- */ // 创建活动记录对象 $article = new Article(); $artic ...

  8. Hive(3)-meta store和hdfs详解,以及JDBC连接Hive

    一. Meta Store 使用mysql客户端登录hadoop100的mysql,可以看到库中多了一个metastore 现在尤其要关注这三个表 DBS表,存储的是Hive的数据库 TBLS表,存储 ...

  9. linux学习--字符设备驱动

    目录 1.字符设备驱动抽象结构 2.设备号及设备节点 2.1 设备号分配与管理 2.2 设备节点的生成 3.打开设备文件 linux驱动有基本的接口进行注册和卸载,这里不再做详细说明,本文主要关注li ...

  10. seleniun 爬取淘宝网

    import re from selenium import webdriver from selenium.common.exceptions import TimeoutException fro ...