参照 草根专栏- 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. iview中table里嵌套i-switch、input、select等

    iview中table内嵌套 input render:(h,params) => { return h('Input',{ props: { value:'', size:'small', } ...

  2. SpringBoot自动装配的原理

    1.SpringApplication.run(AppConfig.class,args);执行流程中有refreshContext(context);这句话. 2.refreshContext(co ...

  3. JAVA基础之控制台输入输出

    ---恢复内容开始--- 输入需要用scanner机制 代码: 启用scanner机制 Scanner input = new Scanner(System.in); //String x= inpu ...

  4. wait();notify();简单例子

    public class Test1{ /** * @param args */ public static void main(String[] args) { new Thread(new Thr ...

  5. The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.报该错误的一种原因。

    今天发现某个action返回404. HTTP Status 404 – Not Found Type Status Report Message /xxx.action Description Th ...

  6. vue-cli项目使用axios实现登录拦截

    登录拦截 一.路由拦截 项目中某些页面需要用户登录后才可以访问,在路由配置中添加一个字段requireAuth 在router/index.js中 . const router = new Route ...

  7. js加载等待效果

    demo01: 加载首页的时候,可能会很缓慢,放一张等待图片. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN ...

  8. QQ空间运营 怎么做一个QQ人气号?

    QQ空间,用户太年轻,他们渐渐长大. 空间,用户消费水准偏低,貌似很难开发,除非玩灰链,否则同等人气,和微信比起来,一个地下,一个天上. 然而,他们快要长大,即将成为消费主力军,难免会转移微信,但情怀 ...

  9. Xshell配色方案推荐

    使用方法: 新建mycolor.xcs文件 复制粘贴如下代码,将文件导入,修改自己喜欢的字体即可 [mycolor] text=00ff80 cyan(bold)=00ffff text(bold)= ...

  10. Hadoop MapReduce自定义数据类型

    一 自定义数据类型的实现 1.继承接口Writable,实现其方法write()和readFields(), 以便该数据能被序列化后完成网络传输或文件输入/输出: 2.如果该数据需要作为主键key使用 ...