参照 草根专栏- 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. PAT——1018. 锤子剪刀布

    大家应该都会玩“锤子剪刀布”的游戏:两人同时给出手势,胜负规则如图所示: 现给出两人的交锋记录,请统计双方的胜.平.负次数,并且给出双方分别出什么手势的胜算最大. 输入格式: 输入第1行给出正整数N( ...

  2. 【luogu P3366 最小生成树】 题解 Prim

    include include include include using namespace std; const int maxn = 505000; int n, m, dis[maxn], v ...

  3. WinCE下SQLCE数据库开发(VS,VB.net,VC++)

    WinCE下SQLCE数据库开发(VS,VB.net,VC++)   WinCE下SQLCE数据库开发 微软的SQL Server数据库由于其功能强大.方便使用,因此在很多行业都被广泛应用.基于智能设 ...

  4. [Medium翻译]RESTful API权威设计指南-设计更好的API

    本文为授权译文.希望查看原文的同学请戳链接:https://hackernoon.com/restful-api-design-step-by-step-guide-2f2c9f9fcdbf 对于我们 ...

  5. linux VMware使用

    contos7 配置网络 使用NAT模式连接本地网络 进入Linux机器配置网络 vi /etc/sysconfig/network-scripts/ifcfg-eth0 TYPE=EthernetP ...

  6. 一点一点看JDK源码(一)Collection体系概览

    一点一点看JDK源码(一)Collection体系概览 liuyuhang原创,未经允许进制转载 本文举例使用的是JDK8的API 目录:一点一点看JDK源码(〇) 1.综述 Collection为集 ...

  7. MyBatis-Plus工具快速入门使用

    MyBatis-plus有什么特色 1.代码生成 2.条件构造器 对我而言,主要的目的是使用它强大的条件构建器. 快速使用步骤: 1.添加pom文件依赖 <dependency> < ...

  8. vsCode中误删了文件,教你怎么恢复

      不要慌!下面开始帮你找到,很简单!

  9. 简单的反编译class文件并重新编译的方法

    在没有.java源码的情况下,如果想修改一个.class文件.可以通过以下步骤实现: 修改前的class文件: 一.反编译.class文件成.java文件. 1.可以使用Java Decompiler ...

  10. 创建jq插件步骤

    无意看了这篇<jQuery插件开发精品教程,让你的jQuery提升一个台阶>文章,现在做一下总结. 一.jQuery插件的创建可以有三种方法 1.通过$.extend()来扩展jQuery ...