Ionic 4 - Как подключить приложение к существующему SQL Server через веб-API? - PullRequest
0 голосов
/ 21 марта 2019

Было задано много похожих вопросов, но ни один из них для этой версии Ionic Framework не получил ответов, которые действительно могут мне помочь.

ФОН:

Я создал приложение и должен получить данные с существующего SQL Server. Из исследований единственный способ сделать это - использовать веб-API в качестве промежуточного программного обеспечения, поскольку Ionic не может напрямую подключаться к SQL Server.

Пожалуйста, обратитесь к этому уроку, поскольку я следовал этому: https://www.youtube.com/watch?v=Js_8ijftKC0&index=21&list=PLaU76WfrROI6LO_YqTDd8ADul3xQoao5L&t=0s

ГДЕ Я НА ТАКОМ ДАЛЬШЕ:

  • Я закончил Ионическую сторону руководства, добавив Сервис, все операции CRUD и т. Д.
  • Я создал веб-API в ASP.NET Web MVC в Visual Studio.
  • API подключен к моей базе данных SQL и позволяет выполнять операции CRUD.

ПРОБЛЕМА:

После многократного выполнения этого урока, не пропустите подсказку. Ни один из методов CRUD в Ionic ничего не возвращает. По запросу ничего не обновляется и не извлекается из базы данных.

  • Чего не хватает в учебнике? Это даже точно?

Любая помощь приветствуется, спасибо заранее.

sql.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestMethod, RequestOptions } from '@angular/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SqlService {
  url:string="http://localhost:50287/api/APIDemo/"
  constructor(private http: Http) { }


getAll(){
  return this.http.get(this.url).pipe(map(res=>res.json()));
}

Create(name) {
  var body={"name":name};
  var header=new Headers({'Content-Type':'application/json'})
  var option=new RequestOptions({method:RequestMethod.Post,headers:header})
  return this.http.post(this.url + "Posttest",body,option).pipe(map(res=>res.json()))
}

Update(id, name) {
  var body={"id":id,"name":name};
  var header=new Headers({'Content-Type':'application/json'})
  var option=new RequestOptions({method:RequestMethod.Post,headers:header})
  return this.http.post(this.url,body,option).pipe(map(res=>res.json()))
}

Read(id) {
  return this.http.get(this.url+id).pipe(map(res=>res.json()))
}

Delete(id) {
  return this.http.delete(this.url+id).pipe(map(res=>res.json()))
}

}

sql.page.ts

import { Component, OnInit } from '@angular/core';
import { SqlService } from '../../services/sql.service'

@Component({
  selector: 'app-sql',
  templateUrl: './sql.page.html',
  styleUrls: ['./sql.page.scss'],
})
export class SqlPage implements OnInit {
  items=[];
  id: string;
  name: string;

  constructor(public sql: SqlService) { 
    this.getAll()
  }

  ngOnInit() {
  }

  getAll() {
    this.items=[];
    this.sql.getAll().subscribe(data=>{
      for(var i=0;i<data.length;i++){
        this.items.push(data[i]);
      }
    })

  }

  Add() {
    if(this.id==null){
    this.sql.Create(this.name).subscribe(data=>{
      this.name="";
      this.getAll();
    })
  }else {
    this.sql.Update(this.id, this.name).subscribe(data=>{
      this.id=null
      this.name=""
      this.getAll()
    })
  }        
}

  Edit(item) {
    this.id = item.id
    this.name = item.name
  }

  Delete(item) {
    this.sql.Delete(item.id).subscribe(data=>{
      this.getAll()
    })

  }

}

sql.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>sql</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label>Name</ion-label>
  <ion-input type="text" [(ngModel)]="id" hidden></ion-input>
  <ion-input type="text" [(ngModel)]="name"></ion-input>
  </ion-item>
  <ion-button (click)="Add()">Add</ion-button>

  <ion-list>
  <ul>
  <li *ngFor="let items of items">
    {{ item.name }}
  <ion-button (click)="Edit(item)">Edit</ion-button>
  <ion-button (click)="Delete(item)">Delete</ion-button>


  </li>
  </ul>
  </ion-list>
</ion-content>

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { HttpClientModule } from '@angular/common/http';
import { EmailComposer } from '@ionic-native/email-composer/ngx';
import { EmailPageModule } from './pages/email/email.module';
import { MapsPageModule } from './pages/maps/maps.module';
import { CallNumber } from '@ionic-native/call-number/ngx';
import { HttpModule } from '@angular/http'
import { SqlService } from './services/sql.service'

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule, EmailPageModule, MapsPageModule, HttpModule],
  providers: [
    StatusBar,
    SplashScreen,
    EmailComposer,
    CallNumber,
    SqlService,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

DemoAPI (C #)

WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace DemoAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableCors(new EnableCorsAttribute(origins: "http://localhost:8100", headers: "*", methods: "*"));

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

APIDemoController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using DemoAPI.Models;

namespace DemoAPI.Controllers
{
    public class APIDemoController : ApiController
    {
        private demoEntities db = new demoEntities();

        // GET: api/APIDemo
        public IQueryable<test> Gettests()
        {
            return db.tests;
        }

        // GET: api/APIDemo/5
        [ResponseType(typeof(test))]
        public IHttpActionResult Gettest(int id)
        {
            test test = db.tests.Find(id);
            if (test == null)
            {
                return NotFound();
            }

            return Ok(test);
        }

        // PUT: api/APIDemo/5
        [ResponseType(typeof(void))]
        public IHttpActionResult Puttest(int id, test test)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != test.id)
            {
                return BadRequest();
            }

            db.Entry(test).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!testExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/APIDemo
        [HttpPost]
        [ResponseType(typeof(test))]
        public HttpResponseMessage Posttest(test test)
        {

            if (test.id == 0)
            {
                if (!ModelState.IsValid)
                {
                    db.tests.Add(test);
                    db.SaveChanges();

                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, test);
                    response.Headers.Location = new Uri(Url.Link("DefaultAPI", new { id = test.id }));
                    return response;
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }
            }
            else
            {
                if (ModelState.IsValid)
                {
                    db.Entry(test).State = EntityState.Modified;
                    try
                    {
                        db.SaveChanges();
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        return Request.CreateResponse(HttpStatusCode.NotFound);
                    }
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, test);
                    response.Headers.Location = new Uri(Url.Link("DefaultAPI", new { id = test.id }));
                    return response;
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }
            }

        }




        // DELETE: api/APIDemo/5
        [ResponseType(typeof(test))]
        public IHttpActionResult Deletetest(int id)
        {
            test test = db.tests.Find(id);
            if (test == null)
            {
                return NotFound();
            }

            db.tests.Remove(test);
            db.SaveChanges();

            return Ok(test);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool testExists(int id)
        {
            return db.tests.Count(e => e.id == id) > 0;
        }
    }
}

1 Ответ

0 голосов
/ 26 марта 2019

Я постараюсь упростить оригинальный ответ.Давайте возьмем HTTP GET запрос.

В вашем сервисе у вас есть:

getAll(){
  return this.http.get(this.url).pipe(map(res=>res.json()));
}

В веб-API у вас есть контроллер, в котором вы будете определять некоторые действия.Ваш HTTP-запрос сопоставляется со следующим маршрутом следующим образом:

routeTemplate: "api/{controller}/{id}"

Routing is how Web API matches a URI to an action

Таким образом, в WebAPI вы должны создать действие, например:

// GET: api/APIDemo/getall
[HttpGet]
[ResponseType(typeof(test))]
public IHttpActionResult GetAll(int id)
{
    test test = db.tests.Find(id);
    if (test == null)
    {
        return NotFound();
    }

    return Ok(test);
}

Ваш пример запроса может быть таким:

localhost:8080/api/apidemo/getall?id=1

Вам также нужно сделать правильный HTTP-запрос, здесь мы получаем все тесты, атрибут [HttpGet] определяет GET.

Вы должны прочитать о Контроллер и Маршрутизация .

edit:

хорошо, поэтому вам нужно создать объект, который соответствует сигнатуре метода в сетиAPI, так что для вашего примера «Создать».

Create(name) {
// use JSON.Stringigy to get an JSON string
  var body=JSON.stringify({id: 1, name:name});
  var header=new Headers({'Content-Type':'application/json'})
  var option=new RequestOptions({method:RequestMethod.Post,headers:header})
  return this.http.post(this.url + "Posttest",body,option).pipe(map(res=>res.json()))
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...