zoukankan      html  css  js  c++  java
  • Angualr6访问API

    参照 草根专栏- 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: 10, pageIndex: 0 });
      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>
  • 相关阅读:
    【WEBAPI】Passing multiple POST parameters to Web API Controller Methods
    【WEBAPI】常用参数传递方法总结
    JavaScript面向对象静态方法私有方法公有方法特权方法
    javascript 封装
    javascript 获取 浏览器body高宽
    Fiddler 教程
    预加载下一张图片
    div页面居中
    关于模块化加载
    chrome本地不能操作iframe
  • 原文地址:https://www.cnblogs.com/fuyouchen/p/9601816.html
Copyright © 2011-2022 走看看