Как передать / сохранить и передать входные данные в веб-сервис в формате 2 и угловой 2?
Я пытаюсь создать форму комментария с оценками. В этой форме я добавил способ пользователям оценивать приложение и оставлять комментарии. Я довольно новичок в angular 2, и мне очень тяжело, как я могу сохранить введенные пользователем данные и / или отправить их в пользовательский веб-сервис, чтобы получить его в следующий раз, когда я открою форму. Вот код на данный момент: comment-star.html:
<ion-header class="top-header">
<ion-toolbar color="primary">
<ion-title class="my-title">
{{title}}
</ion-title>
<ion-buttons start>
<button ion-button (click)="dismiss('')">
<span showWhen="ios">x</span>
<ion-icon name="md-close" showWhen="android,windows"></ion-icon>
</button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content padding no-bounce>
<ion-label class="label">How would you rate our app?</ion-label>
<ion-grid no-padding no-margin class="ion-rating-container">
<ion-row>
<fieldset class="rating">
<input type="radio"
value="5"
[name]="inpustName"
[checked]="rating===5" />
<label title="Excellent!" (click)='onClick(5)'>5 stars</label>
<input type="radio"
value="4"
[name]="inpustName"
[checked]="rating===4" />
<label title="Pretty good" (click)='onClick(4)'>4 stars</label>
<input type="radio"
value="3"
[name]="inpustName"
[checked]="rating===3" />
<label title="Satisfactory" (click)='onClick(3)'>3 stars</label>
<input type="radio"
value="2"
[name]="inpustName"
[checked]="rating===2" />
<label title="Not good" (click)='onClick(2)'>2 stars</label>
<input type="radio"
value="1"
[name]="inpustName"
[checked]="rating===1" />
<label title="Terrible" (click)='onClick(1)'>1 star</label>
</fieldset>
</ion-row>
</ion-grid>
<ion-label class="label">Tell us how we can improve our app?</ion-label>
<ion-textarea no-bounce class="text-area" rows="11" placeholder="Add a review"></ion-textarea>
<button ion-button class="button-text"round (click)="dismiss('')">Submit</button>
</ion-content>
комментарии-star.scss:
comment-star {
.button-text {
width:40%;
margin-left: 30%;
margin-top:5%;
}
.text-area{
margin-left:5%;
border:solid 1px black;
width:90%;
height:40%;
}
button button-ios, button button-md{
width:40%;
margin-left: 30%;
margin-top:5%;
}
.label{
color:black;
font-size:15px;
margin-left:5%;
}
.inner {
width: 50%;
margin: 0 auto;
}
/***************************
Pulls the stars container to the left
***************************/
.rating {
float:right;
overflow:hidden;
color:#ddd;
border-color:white;
border-width: 0;
}
/***************************
Hides the radio buttons
***************************/
.rating:not(:checked) > input {
position:absolute;
top:-9999px;
clip:rect(0,0,0,0);
}
/***************************
Default stars styles
***************************/
.rating:not(:checked) > label {
float:right;
width:1em;
padding:1em;
overflow:hidden;
white-space:nowrap;
cursor:pointer;
font-size:180%;
line-height:1.3;
color:#ddd;
}
/***************************
Adds the star symbol to the labels
***************************/
.rating:not(:checked) > label:before {
content: '★ ';
}
/***************************
Colour for the applied rating stars
***************************/
.rating > input:checked ~ label {
color: #f70;
}
/***************************
Colour for hovered stars when increasing the rating
***************************/
.rating:not(:checked) > label:hover,
.rating:not(:checked) > label:hover ~ label {
color: gold;
}
/***************************
Colour for hovered stars when decreasing the rating
***************************/
.rating > input:checked ~ label:hover,
.rating > input:checked ~ label:hover ~ label,
.rating > label:hover ~ input:checked ~ label {
color: #ea0;
}
}
комментарии-star.ts
import { NavController, ViewController,NavParams} from 'ionic-angular';
import {Component, Input, Output, EventEmitter} from '@angular/core';
import { App } from 'ionic-angular';
import { Http } from '@angular/http';
/*
Generated class for the CommentStar page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
@Component({
selector: 'comment-star',
templateUrl: 'comment-star.html',
})
export class Commentstar{
title: string = "Rate & Review"
@Input() rating: number;
@Input() itemId: number;
@Output() ratingClick: EventEmitter<any> = new EventEmitter<any>();
inpustName:string;
public firstParam;
constructor(public nav: NavController,public viewCtrl: ViewController,private app: App,http: Http,public navParams: NavParams) {
this.firstParam = navParams.get("");
}
ngOnInit() {
this.inpustName = this.itemId + '_rating';
}
onClick(rating: number): void {
this.rating = rating;
this.ratingClick.emit({
itemId: this.itemId,
rating: rating
});
console.log("rating is:", rating);
}
dismiss(item) {
this.viewCtrl.dismiss(item)
}
submit(item){
this.viewCtrl.dismiss(item)
}
}
Любые учебники или ссылки для этого тоже будут полезны.
1 ответ
Ваш вопрос подразумевает, что у вас нет веб-службы. Поэтому я бы порекомендовал создать REST Api с ядром.net и запросами POST и GET к этому API для сохранения и получения данных.
Чтобы сохранить его локально, в ionic 2 я рекомендую плагин Storage, показанный в документации Ionic v2: https://ionicframework.com/docs/storage/
Я создал службу, которая называется StorageService, где я делаю все настройки и получения локальных данных.
Сервис:
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { Storage } from '@ionic/storage';
@Injectable()
export class StorageService {
public storageKeys: string[] = ['ratings', 'user']
constructor(public storage: Storage) { }
// AUTH STORAGE
public setRatingStorage(rating: any[]) {
this.storage.set('ratings', {ratings: ratings, time: Date.now()})
.catch(error => console.log(JSON.stringify(error)));
}
public getRatingStorage() {
return this.storage.get('ratings')
.catch(error => console.log(JSON.stringify(error)));
}
// ...
}
Компонент / другой сервис, внедряющий StorageService
setRatings(ratings: any[]) {
// Ratings is an array of ratings that you should push to, then
// when you want to save/confirm the rating, call this and set
// the storage. So that you can retrieve it later or in other
// places throughout the application.
this._storage.setRatingStorage(ratings);
}
getRatings(): Promise<any> {
this._storage.getRatingStorage()
.then(storedRatingData => {
of(storedRatingData && storedRatingData..length > 0)
// Where this.ratings is a local variable that you can manipulate/display
this.ratings = storedRatingData.ratings;
}).catch(err => console.log(err));
}