我有一个用VB.NET开发的REST Web服务和一个MS Access数据库。我试图从我的Angular应用程序中获取一个字符串值,然后将其插入到只包含一个表的数据库中,如下所示。
现在我尝试使用Web服务方法将Angular应用程序中的值SriLanka插入到数据库中。虽然我能够插入值,但我不认为我已经实现了http.post()方法。
这是我的Angular代码:
app.component.ts
import { Component, Inject } from '@angular/core';
import { AppStore } from './app.store';
import { AppState } from './app.state';
import { Store } from 'redux';
import * as DummyService from './Dummy.service';
import * as DummyActions from './Dummy.actions';
import { HttpClient } from '@angular/common/http';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
counter: number;
country: string;
http$: HttpClient;
constructor( @Inject(AppStore) private store: Store<AppState>, http$: HttpClient) {
this.http$ = http$;
}
ngOnInit() {
this.Load(this.store, this.http$, this.country);
}
Load(store: Store<AppState>, http$: HttpClient, country: string) {
store.subscribe(() => this.readState());
this.readState();
DummyService.Load(this.store, this.http$, 'SriLanka');
}
}
Dummy.service.ts
import * as Redux from 'redux';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import * as Model from './app.state';
import * as Actions from './Dummy.actions';
export const PASS = "PASS";
export const FAIL = "FAIL";
export const OMIT = "OMIT";
export function Load(store: Redux.Store<Model.AppState>, http$: HttpClient, country: string) {
try {
http$.get('assets/AppOptions.json',{responseType: "text"}).subscribe(data => {
try {
var oAppOptions:Model.ApplicationOptions = JSON.parse(data);
store.getState().oApplicationOptions = oAppOptions;
InsertCountryDetails(store, http$, country);
}catch(e) {
alert("Unable to parse the AppOptions.json file.");
}
}, function (error:HttpErrorResponse) {
alert("An error occured while reading the AppOption file.");
});
} catch (e) {
throw new Error("DummyService::Load() Exception : " + e);
}
}
function InsertCountryDetails(store: Redux.Store<Model.AppState>, http$: HttpClient, country: string){
var WebServiceDataJson: string = JSON.stringify(store.getState().WebServiceData);
var Servicelink: string = store.getState().oApplicationOptions.WebServiceLink;
let url = Servicelink + "InsertCountryDetails/" + encodeURI(WebServiceDataJson);
http$.post(url, country).subscribe((res: Response) => {
console.log(res);
});
}
这是我的DummyWebService.vb代码:
Imports System.ServiceModel
Imports System.ServiceModel.Web
<ServiceContract()>
Public Interface IDummyWebService
<OperationContract>
<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="InsertCountryDetails/{WebServiceDataJson}/{Country}")>
Sub InsertCountryDetails(ByVal WebServiceDataJson As String, ByVal Country As String)
End Interface
这是DummyWebService.svc.vb代码:
Imports System.Web.Script.Serialization
Imports DynamicJsonParser
Imports DummyWebService.ServerCallBackResult
' NOTE: You can use the "Rename" command on the context menu to change the class name "Service1" in code, svc and config file together.
' NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.vb at the Solution Explorer and start debugging.
Public Class Service1
Implements IDummyWebService
Public Sub New()
End Sub
Public Sub InsertCountryDetails(ByVal WebServiceDataJson As String, ByVal Country As String) Implements IDummyWebService.InsertCountryDetails
RequestLog("InsertCountryDetails WebServiceDataJson : " & WebServiceDataJson & ", Country : " & Country)
Dim callBack As ServerCallBackResult = New ServerCallBackResult
Try
Dim oWebServiceData As WebServiceData = WebServiceData.GetWebServiceData(WebServiceDataJson)
Dim Dummy As New Dummy(oWebServiceData)
Try
Dummy.InsertCountryDetails(Country)
Catch ex As Exception
Throw ex
Finally
Dummy.Dispose()
End Try
Catch ex As Exception
callBack.Status = EnumStatus.FAIL.ToString
callBack.ErrorMsg = "DummyWebService::InsertCountryDetails(WebServiceDataJson, Country) Exception : " + CheckAndGetOleDbExceptionMessage(ex.Message)
ExceptionLog(callBack.ErrorMsg)
End Try
End Sub
End Class
这是Dummy.vb代码:
Imports System.Data
Imports System.Data.OleDb
Imports System.Configuration
Imports System.Web
Public Class Dummy
Implements IDisposable
Private oDataInterface As DataInterface
Private oWebServiceData As WebServiceData
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
oDataInterface.Dispose()
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
#Region " IDisposable Support "
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
Public Sub New(ByRef oWebServiceData_in As WebServiceData)
Try
Me.oDataInterface = New DataInterface()
Me.oWebServiceData = oWebServiceData_in
Catch ex As Exception
Throw New Exception("Dummy::New() Exception : " + ex.Message)
End Try
End Sub
Public Sub InsertCountryDetails(ByVal Country As String)
Try
oDataInterface.InsertCountryDetails(Country)
Catch ex As Exception
Throw New Exception("Dummy::GetColorFromCountryName(Country) Exception : " + ex.Message)
End Try
End Sub
End Class
这是DataInterface.vb代码:
Imports System.Data.OleDb
Imports System.Data
Public Class DataInterface
Implements IDisposable
Private oConn As OleDbConnection
Private disposedValue As Boolean = False
Private DataFilter As String = String.Empty
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
CloseConnection()
End If
End If
Me.disposedValue = True
End Sub
Private Sub CloseConnection()
Try
oConn.Close()
oConn = Nothing
Catch ex As Exception
Throw New Exception("DataInterface::CloseConnection() Exception : " + ex.Message)
End Try
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
Public Sub InsertCountryDetails(ByVal Country As String)
Try
Dim countryName As String
countryName = Country
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Angular Projects\Dummy\DummyDatabase.accdb"
Using myconnection As New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String = "INSERT INTO Countries (Country) VALUES (countryName)"
Using cmd As New OleDbCommand(sqlQry, myconnection)
cmd.Parameters.AddWithValue("@countryName", countryName)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Throw New Exception("DataInterface::GetColor(Country) Exception : " + ex.Message)
End Try
End Sub
实际上我是.NET和Angular的初学者,而且我没有100%保证我所做的是正确与否。那么,任何人都可以告诉我在我的情况下使用http.post()的方式吗?
答案 0 :(得分:0)
我不做很多VB.Net,但这里有一些关于你的Angular代码的建议
你不想从这里获得你的导入,而是来自@ angular / core doc在这里https://angular.io/api/core/OnInit
如果你在构造函数中添加私有的参数,你不需要分配它们,它是一个有角度的捷径。有关的文档是here
app.component.ts
import { Component, Inject, OnInit, OnDestroy } from '@angular/core';
import { AppStore } from './app.store';
import { AppState } from './app.state';
import { Store } from 'redux';
import * as DummyService from './Dummy.service';
import * as DummyActions from './Dummy.actions';
import { HttpClient } from '@angular/common/http';
// import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
counter: number;
country: string;
subscription: Subscription;
constructor( @Inject(AppStore) private store: Store<AppState>, private http$: HttpClient) {
}
ngOnInit() {
this.Load(this.store, this.http$, this.country);
}
Load(store: Store<AppState>, http$: HttpClient, country: string) {
**// you want to unsubscribe to this in the lifecycle hook ngOnDestroy**
this.subscription = store.subscribe(() => this.readState());
this.readState();
DummyService.Load(this.store, this.http$, 'SriLanka');
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
我更喜欢我的服务是可注射的,我也不想在服务中订阅我的http请求,因为这意味着我必须取消订阅以避免内存泄漏,所以我更喜欢他们返回他们的结果或承诺。无论我在哪里使用该服务,我都会订阅那里的承诺,以便我可以放弃取消订阅。此外,如果您的服务是可注射的,则需要在其打算使用的模块中提供。如果它在多个模块中使用,您可以将其包含在应用程序模块中。
import { Injectable } from '@angular/core';
import * as Redux from 'redux';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import * as Model from './app.state';
import * as Actions from './Dummy.actions';
export const PASS = "PASS";
export const FAIL = "FAIL";
export const OMIT = "OMIT";
@Injectable()
export class DummyService {
constructor(private store: ReducStore<Model.AppState>, private http$: HttpClient) {}
Load(country: string) {
try {
this.http$.get('assets/AppOptions.json',{responseType: "text"}).subscribe(data => {
try {
var oAppOptions:Model.ApplicationOptions = JSON.parse(data);
this.store.getState().oApplicationOptions = oAppOptions;
InsertCountryDetails(store, http$, country);
}catch(e) {
alert("Unable to parse the AppOptions.json file.");
}
}, function (error:HttpErrorResponse) {
alert("An error occured while reading the AppOption file.");
});
} catch (e) {
throw new Error("DummyService::Load() Exception : " + e);
}
}
InsertCountryDetails(country: string){
var WebServiceDataJson: string = JSON.stringify(this.store.getState().WebServiceData);
var Servicelink: string = store.getState().oApplicationOptions.WebServiceLink;
let url = Servicelink + "InsertCountryDetails/" + encodeURI(WebServiceDataJson);
return this.http$.post(url, country);
}
我希望这很有帮助。