我一直在将一些代码转换为异步方法.我有一个工作单元/存储库/服务设计模式,我的存储库看起来像这样:
public class Repository<T> : IDisposable, IRepository<T> where T : class
{
private readonly DbContext context;
private readonly DbSet<T> dbEntitySet;
public Repository(DbContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
this.dbEntitySet = context.Set<T>();
}
public IQueryable<T> GetAll(params string[] includes)
{
IQueryable<T> query = this.dbEntitySet;
foreach (var include in includes)
query = query.Include(include);
return query;
}
public void Create(T model)
{
this.dbEntitySet.Add(model);
}
public void Update(T model)
{
this.context.Entry<T>(model).State = EntityState.Modified;
}
public void Remove(T …Run Code Online (Sandbox Code Playgroud) 我已经将 .Net 对象作为驼峰式 JSON 返回,并且我已经这样做了:
// Web API configuration and services
var formatters = config.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var serializerSettings = jsonFormatter.SerializerSettings;
// Remove XML formatting
formatters.Remove(config.Formatters.XmlFormatter);
jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
// Configure our JSON output
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
serializerSettings.Formatting = Formatting.Indented;
Run Code Online (Sandbox Code Playgroud)
这一切都工作正常,但今天我发布到外部 API 并收到错误,事实证明问题在于使用 Pascal 大小写而不是 Camel 大小写的 json 格式。我发布的数据如下所示:
{"CartId":"8fb3792f-81af-45e6-92f6-f08366624f1e","Id":"944990015513953203","Quantity":5}
Run Code Online (Sandbox Code Playgroud)
我四处搜寻,找到了一种将数据转换为驼峰式大小写的解决方案,如下所示:
var serializer = new JsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var json = JObject.FromObject(model, serializer);
Run Code Online (Sandbox Code Playgroud)
但正如您所猜测的,这并不是真正合适,因为我不想在每个控制器的每个 POST 操作中都这样做。我假设上面的 WebApiConfig 将应用于所有响应和请求。
有谁知道如何打开全局驼峰式开关?
我正在尝试使用 .net core web api。我创建了一个静态方法来注册我的控制器,如下所示:
public static class RegistrationExtensions
{
public static void RegisterApplicationServices(this IServiceCollection services, IServiceProvider serviceProvider)
{
services.RegisterSingletons();
services.RegisterRequests();
services.RegisterTransient(serviceProvider);
}
public static void RegisterSingletons(this IServiceCollection services)
{
services.AddSingleton<Configuration>();
}
public static void RegisterRequests(this IServiceCollection services)
{
services.AddScoped<ISettingsService, SettingsService>();
}
public static void RegisterTransient(this IServiceCollection services, IServiceProvider serviceProvider)
{
var config = serviceProvider.GetService<Configuration>();
services.AddDbContext<InteractiveChoicesContext>(m => m.UseSqlServer(config.ConnectionString));
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我想解析包含我的ConnectionString 的Configuration类,我将其传递给DbContext。请解决我尝试使用IServiceProvider的配置,该配置注入RegisterApplicationServices方法。
为了调用这个方法,我将Startup类的 …
c# entity-framework-core asp.net-core-mvc asp.net-core asp.net-core-webapi
我已经像这样设置了我的角度项目:
https://angularfirebase.com/lessons/shorten-typescript-imports-in-an-angular-project/
但它似乎不起作用。我的tsconfig看起来像这样:
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
],
"module": "es2015",
"baseUrl": "./",
"paths": {
"@data/*": ["src/app/core/data/*"],
"@constants/*": ["src/app/core/constants/*"],
"@models/*": ["src/app/core/models/*"],
"@services/*": ["src/app/core/services/*", "src/app/core/sessions/*"],
"@shared/*": ["src/app/shared/*"]
}
}
}
Run Code Online (Sandbox Code Playgroud)
我煞费苦心地浏览了整个应用程序,并用这些新路径替换了所有“长”路径,当我尝试执行此操作时,ng serve我遇到了很多错误。
这里有几个:
src/app/categories/categories.component.ts(3,31) 中的错误:错误 TS2307:找不到模块“@constants/animations”。
src/app/core/components/animations/animations.component.ts(3,34): 错误 TS2307: 找不到模块“@constants/animations”。
src/app/core/components/animations/animations.component.ts(4,34): 错误 TS2307: 找不到模块“@services/animation.service”。
src/app/core/components/spinner/spinner.component.ts(3,32): 错误 TS2307: 找不到模块“@services/loading.service”。
有负载,当我查看实际组件/模块时,智能感知显示没有问题。有谁知道为什么会发生这种情况?
我正在建立一个库,我希望我的其他项目可以使用它。我正在尝试将配置文件传递到我定义的模块,如下所示:
@NgModule({
declarations: [ImageComponent],
imports: [CommonModule],
})
export class ImagesModule {
static forRoot(config: ImagesConfig): ModuleWithProviders<ImagesModule> {
return {
ngModule: ImagesModule,
providers: [{ provide: ImagesConfig, useValue: config }],
};
}
}
export class ImagesConfig {
cloudName: string;
}
Run Code Online (Sandbox Code Playgroud)
这看起来不错,但现在我想在实际模块中使用 cloudName ,如下所示:
@NgModule({
declarations: [ImageComponent],
imports: [
CommonModule,
CloudinaryModule.forRoot(Cloudinary, {
config.cloudName,
}),
],
})
export class ImagesModule {
static forRoot(config: ImagesConfig): ModuleWithProviders<ImagesModule> {
return {
ngModule: ImagesModule,
providers: [{ provide: ImagesConfig, useValue: config }],
};
}
}
export class ImagesConfig { …Run Code Online (Sandbox Code Playgroud) 如果我创建一个控制器实现IDisposable,我认为该Dispose方法仍然不会被GC调用.所以这意味着我必须添加:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
if (!isDalDisposed)
{
isDalDisposed = true;
if (disposing)
DAL.Dispose();
}
base.Dispose(disposing);
}
Run Code Online (Sandbox Code Playgroud)
我已经读到使用Object.Finalize是不好的做法,应尽可能避免使用.
我遇到的问题是我的"服务"是在默认构造函数中创建的,它不允许我使用using语句来控制每个服务的生命周期.那么,处理这个问题的正确方法是什么?
我正在使用 Angular4 并尝试安装分析。我遵循了本指南:
https://blog.thecodecampus.de/angular-2-include-google-analytics-event-tracking/
但是当我尝试构建我的项目时,出现错误:
错误 TS2304:找不到名称“ga”。
我已经检查了我的 package.json 并且我已经"@types/google.analytics": "0.0.38",安装在我的devDependencies 中。当我开始打字时,我可以看到智能感知知道它是一种UniversalAnalytics.ga类型,但我无法让它工作。
我尝试将代码更改为:
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
let ga: Function;
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
Run Code Online (Sandbox Code Playgroud)
它可以编译,但在 console.log 中我收到一条错误消息:
Uncaught (in promise): TypeError: ga is not a function
如果我改成这样:
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
let ga: any;
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
Run Code Online (Sandbox Code Playgroud)
我犯了同样的错误。有谁知道为什么?
这是完整的代码:
import { Component, OnInit, AfterViewChecked, AfterViewInit } from "@angular/core";
import …Run Code Online (Sandbox Code Playgroud) 我有一个应用程序,我已设法将其转换为 Angular Universal(应我的客户要求)。我使用命令运行了我的应用程序,npm run serve:ssr并将我的浏览器指向http://localhost:4000。
现在我想部署。我已经运行npm run build:ssr它创建了一个 dist 文件夹。dist 文件夹中没有“普通”角度文件。它相对稀疏,它有:
如果我将这些 ftp 传输到我的 azure 站点(就像我过去使用普通 angular 应用程序所做的那样),它就不起作用。我收到一个错误:
您无权查看此目录或页面。
因此,我尝试使用 VSTS 设置 CI,并按照我发现的一些步骤来发布 angular Universal(尽管它们不是很清楚)。这是我的yaml文件:
queue:
name: Hosted VS2017
demands: npm
steps:
- task: NodeTool@0
displayName: 'Use Node 8.x'
inputs:
versionSpec: 8.x
- task: Npm@1
displayName: 'npm install'
inputs:
verbose: false
- task: Npm@1
displayName: 'npm run'
inputs:
command: custom
verbose: false
customCommand: 'run …Run Code Online (Sandbox Code Playgroud) 所以我一直在尝试将我的应用程序转换为角度通用的,并且在大多数情况下它都很好。但我之前读过一些“陷阱”:https ://github.com/onespeed-articles/angular-universal-gotchas
这表明我不应该使用timeout这令人讨厌的东西,因为在AngularJS中,你用它来在视图渲染后触发事件,这样你就可以确保元素的尺寸是正确的,等等。
我还读到它仍然存在于Angular 6中,所以我有这个指令:
import { Directive, ElementRef, AfterViewInit, Input, HostListener } from '@angular/core';
@Directive({
selector: '[pyb-button-group]'
})
export class ButtonGroupDirective implements AfterViewInit {
@Input() className: string;
@HostListener('window:resize', ['$event'])
onResize() {
let resize = this.resize;
let element = this.element;
let className = this.className;
setTimeout(function () {
resize(element, className);
}, 500);
}
constructor(private element: ElementRef) {
}
ngAfterViewInit() {
this.resize(this.element, this.className);
}
resize(nativeElement, className) {
let elements = nativeElement.nativeElement.getElementsByClassName(className || 'btn-choice');
let headerHeight …Run Code Online (Sandbox Code Playgroud) 我不确定我在这里做错了什么。
我正在尝试使用此文档将结帐工具用于条带:https : //stripe.com/docs/payments/checkout/accept-a-payment
我已将 API 配置为仅将 checkoutid 作为字符串返回。Angular 服务只是调用控制器。当我运行我的代码时,我实际上得到了一个不错的 200 响应,我可以在响应正文中看到结帐 ID,但是 Angular 抛出了一个错误:
SyntaxError: JSON.parse () at XMLHttpRequest.onLoad ( https://127.0.0.1:4200/vendor.js:18780:51 ) at ZoneDelegate.invokeTask位置 0 处的意外标记 c
该服务如下所示:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { environment } from '@environments/environment';
@Injectable({
providedIn: 'root',
})
export class StripeService {
private endpoint: string = 'stripe';
constructor(private http: HttpClient) {}
checkout(priceId: string) {
return this.http
.get<string>(`${environment.apiUrl}/${this.endpoint}/${priceId}`)
.pipe(
map((response) => …Run Code Online (Sandbox Code Playgroud) angular ×6
c# ×4
json ×2
asp.net-core ×1
async-await ×1
asynchronous ×1
azure ×1
azure-devops ×1
idisposable ×1
linq ×1
typescript ×1