参照 草根专栏- 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. javaWeb中怎么获取提交表单里面的值

    在javaWeb中如何获得html文件中的表单里面的值? <!DOCTYPE html> <html> <head> <meta charset=" ...

  2. Poj2010 Moo University - Financial Aid

    题意的话,就看其他人的吧 概括:二分中位数 大体上便是二分一个中位数,带入检验,若分数比他小的有\(\lfloor n/2 \rfloor\)个,分数比他的大的也有这么多,而且贪心的买,花费小于预算. ...

  3. 时间比较方法DateTime.Compare

    格式:DateTime.Compare(datetime1, datetime2) 参数为时间格式,为第一个参数比较第二个参数,返回小于0的值,等于0或大于0的值. 实例: string st1 = ...

  4. UICollectionView的水平流水布局自定义layout

    最近做合创共美的商城项目,遇到发货地址的不配送地区,是做一个弹出框,弹出框的布局是根据地名字数长短不齐的标签. 本来也可以用tableview来做的.只不过多建几个tableviewcell就可以了. ...

  5. javascript 正则表达式之分组与前瞻匹配详解

    本文主要讲解javascript 的正则表达式中的分组匹配与前瞻匹配的,需要对正则的有基本认识,本人一直对两种匹配模棱不清.所以在这里总结一下,如有不对,还望大神指点. 1.分组匹配: 1.1捕获性分 ...

  6. Django学习笔记1

    重点在注释# 1.views.py from django.shortcuts import render from django.http import * #from django.templat ...

  7. LinkedList的源码分析(基于jdk1.8)

    1.初始化 public LinkedList() { } 并未开辟任何类似于数组一样的存储空间,那么链表是如何存储元素的呢? 2.Node类型 存储到链表中的元素会被封装为一个Node类型的结点.并 ...

  8. Python学习 :正则表达式

    正则表达式 python 使用正则表达式(re)来进行匹配引擎搜索 正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符.及这些特定字符的组合,组成一个“规则字符串” 关于正则表达式 ...

  9. 在线升级python3.3版本

    1.sudo su 2.wget -P /usr/local  http://www.python.org/ftp/python/3.3.0/Python-3.3.0.tgz    #指定下载到目录/ ...

  10. C语言经典程序100例

    -------------------------------------------------------------------------------- [程序1] 题目:古典问题:有一对兔子 ...