Browse Source

try to get the list of polls

creation-form
tykayn 2 years ago
parent
commit
1b49231d92
  1. 40
      src/app/core/services/api.service.ts
  2. 30
      src/app/core/services/poll.service.ts
  3. 2
      src/app/features/administration/form/form.component.html
  4. 4
      src/app/features/administration/form/form.component.ts
  5. 5
      src/app/shared/components/ui/copy-text/copy-text.component.html
  6. 0
      src/app/shared/components/ui/copy-text/copy-text.component.scss
  7. 24
      src/app/shared/components/ui/copy-text/copy-text.component.spec.ts
  8. 23
      src/app/shared/components/ui/copy-text/copy-text.component.ts
  9. 3
      src/app/shared/components/ui/erasable-input/erasable-input.component.html
  10. 0
      src/app/shared/components/ui/erasable-input/erasable-input.component.scss
  11. 24
      src/app/shared/components/ui/erasable-input/erasable-input.component.spec.ts
  12. 22
      src/app/shared/components/ui/erasable-input/erasable-input.component.ts
  13. 4
      src/app/shared/shared.module.ts
  14. 2
      src/environments/environment.ts

40
src/app/core/services/api.service.ts

@ -4,7 +4,10 @@ import { environment } from 'src/environments/environment';
import { Answer } from '../enums/answer.enum';
import { Poll } from '../models/poll.model';
import { HttpHeaders } from '@angular/common/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { ToastService } from './toast.service';
import { LoaderService } from './loader.service';
const apiVersion = environment.api.versionToUse;
const currentApiRoutes = environment.api.version[apiVersion];
@ -16,6 +19,8 @@ const apiEndpoints = environment.api.endpoints;
providedIn: 'root',
})
export class ApiService {
private useDevLocalServer = true;
private devLocalServerBaseHref = 'http://localhost:8000/';
private axiosInstance: AxiosInstance;
private readonly pollsEndpoint = apiEndpoints.polls.name;
@ -25,17 +30,42 @@ export class ApiService {
private readonly usersEndpoint = apiEndpoints.users.name;
private readonly usersPollsEndpoint = apiEndpoints.users.polls.name;
private readonly usersPollsSendEmailEndpoint = apiEndpoints.users.polls.sendEmail.name;
private static loader: LoaderService;
constructor() {
constructor(private http: HttpClient, private loader: LoaderService, private toastService: ToastService) {
this.axiosInstance = axios.create({ baseURL: apiBaseHref });
this.axiosInstance.defaults.timeout = 2500;
this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/json';
this.axiosInstance.defaults.headers.post['Accept'] = 'application/json';
this.axiosInstance.defaults.headers.post['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
this.axiosInstance.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
this.axiosInstance.defaults.headers.post['Charset'] = 'UTF-8';
}
//////////////////////
// CREATE OR UPDATE //
//////////////////////
public async createPoll(poll: Poll): Promise<string> {
public async createPoll(poll: Poll): Promise<Subscription> {
// this.loader.setStatus(true);
console.log('config', poll);
// const baseHref = this.useDevLocalServer ? 'http://localhost:8000' : apiBaseHref;
// return this.http
// .post(`${baseHref}${currentApiRoutes['api_new_poll']}`, poll, ApiService.makeHeaders())
// .subscribe(
// (res: Observable<any>) => {
// // redirect to the page to administrate the new poll
// this.toastService.display('Sondage Créé');
//
// console.log('res', res);
// // this.updateCurrentPollFromResponse(res);
//
// this.loader.setStatus(false);
// },
// (e) => {
// ApiService.handleError(e);
// }
// );
try {
console.log('currentApiRoutes', currentApiRoutes);
return await this.axiosInstance.post(`${apiBaseHref}${currentApiRoutes['api_new_poll']}`, poll);
@ -213,12 +243,13 @@ export class ApiService {
* prepare headers like the charset and json type for any call to the backend
* @param bodyContent?
*/
private makeHeaders(bodyContent?: any) {
static makeHeaders(bodyContent?: any) {
const headerDict = {
Charset: 'UTF-8',
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Accept,Accept-Language,Content-Language,Content-Type',
'Access-Control-Allow-Origin': '*',
};
@ -231,6 +262,7 @@ export class ApiService {
}
private static handleError(error): void {
// this.loader.setStatus(true);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx

30
src/app/core/services/poll.service.ts

@ -1,6 +1,6 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';
import { BehaviorSubject, Observable } from 'rxjs';
import { BehaviorSubject, Observable, Subscription } from 'rxjs';
import { Answer } from '../enums/answer.enum';
import { Choice } from '../models/choice.model';
@ -10,8 +10,8 @@ import { ApiService } from './api.service';
import { ToastService } from './toast.service';
import { UserService } from './user.service';
import { UuidService } from './uuid.service';
import { Form } from '@angular/forms';
import { PollConfig } from '../../features/old-stuff/config/PollConfig';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root',
@ -21,6 +21,7 @@ export class PollService implements Resolve<Poll> {
public readonly poll: Observable<Poll | undefined> = this._poll.asObservable();
constructor(
private http: HttpClient,
private router: Router,
private apiService: ApiService,
private userService: UserService,
@ -28,6 +29,11 @@ export class PollService implements Resolve<Poll> {
private toastService: ToastService
) {}
/**
* auto fetch a poll when route is looking for one in the administration pattern
* @param route
* @param state
*/
public async resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<Poll> {
const segments: string[] = state.url.split('/');
const wantedSlug: string = segments.includes('poll') ? segments[segments.indexOf('poll') + 1] : '';
@ -48,6 +54,20 @@ export class PollService implements Resolve<Poll> {
}
}
getAllAvailablePolls() {
const baseHref = environment.api.version.apiV1.baseHref;
console.log('getAllAvailablePolls baseHref', baseHref);
const headers = ApiService.makeHeaders();
console.log('getAllAvailablePolls headers', headers);
try {
this.http.get(`${baseHref}/poll`, headers).subscribe((res: Observable<any>) => {
console.log('getAllAvailablePolls res', res);
});
} catch (e) {
console.log('getAllAvailablePolls e', e);
}
}
public async loadPollBySlug(slug: string): Promise<void> {
console.log('slug', slug);
if (slug) {
@ -96,7 +116,7 @@ export class PollService implements Resolve<Poll> {
}
public async saveCurrentPoll(): Promise<void> {
const pollUrl: string = await this.apiService.createPoll(this._poll.getValue());
const pollUrl: Subscription = await this.apiService.createPoll(this._poll.getValue());
// TODO: Maybe handle the url to update currentPoll according to backend response
if (pollUrl) {
console.log('pollUrl', pollUrl);
@ -162,7 +182,7 @@ export class PollService implements Resolve<Poll> {
return list;
}
newPollFromForm(form: any) {
newPollFromForm(form: any): Poll {
const newpoll = new Poll(
this.userService.getCurrentUser(),
this.uuidService.getUUID(),

2
src/app/features/administration/form/form.component.html

@ -355,6 +355,8 @@
{{ form.controls.slug.value }}
</strong>
</span>
<app-copy-text [textToCopy]="form.controls.slug.value"></app-copy-text>
<button
mat-button
*ngIf="form.controls.slug.value"

4
src/app/features/administration/form/form.component.ts

@ -50,6 +50,10 @@ export class FormComponent implements OnInit {
ngOnInit(): void {
this.initFormDefault();
// TO remove after
// this.createPoll();
const pollsAvailable = this.pollService.getAllAvailablePolls();
console.log('pollsAvailable', pollsAvailable);
}
public createPoll(): void {

5
src/app/shared/components/ui/copy-text/copy-text.component.html

@ -0,0 +1,5 @@
<button (click)="copy()" class="btn btn--primary btn--outline" id="copyLink">
<i class="fa fa-copy" aria-hidden="true"></i>
{{ 'admin.copy_link' | translate }}
<span *ngIf="displayContentToCopy"> " {{ textToCopy }}" </span>
</button>

0
src/app/shared/components/ui/copy-text/copy-text.component.scss

24
src/app/shared/components/ui/copy-text/copy-text.component.spec.ts

@ -0,0 +1,24 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CopyTextComponent } from './copy-text.component';
describe('CopyTextComponent', () => {
let component: CopyTextComponent;
let fixture: ComponentFixture<CopyTextComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [CopyTextComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CopyTextComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

23
src/app/shared/components/ui/copy-text/copy-text.component.ts

@ -0,0 +1,23 @@
import { Component, Input, OnInit } from '@angular/core';
import { ClipboardService } from 'ngx-clipboard';
import { ToastService } from '../../../../core/services/toast.service';
@Component({
selector: 'app-copy-text',
templateUrl: './copy-text.component.html',
styleUrls: ['./copy-text.component.scss'],
})
export class CopyTextComponent implements OnInit {
@Input() public textToCopy: string;
public displayContentToCopy = false;
constructor(private _clipboardService: ClipboardService, private toastService: ToastService) {}
ngOnInit(): void {}
public copy(): void {
this._clipboardService.copyFromContent(this.textToCopy);
this.toastService.display(`Texte copié : ${this.textToCopy}`);
}
}

3
src/app/shared/components/ui/erasable-input/erasable-input.component.html

@ -0,0 +1,3 @@
<button class="erase btn btn--warning" *ngIf="inputModel.length" (click)="eraseInput()">
<i class="fa fa-times" aria-hidden="true"></i>
</button>

0
src/app/shared/components/ui/erasable-input/erasable-input.component.scss

24
src/app/shared/components/ui/erasable-input/erasable-input.component.spec.ts

@ -0,0 +1,24 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ErasableInputComponent } from './erasable-input.component';
describe('ErasableInputComponent', () => {
let component: ErasableInputComponent;
let fixture: ComponentFixture<ErasableInputComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ErasableInputComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ErasableInputComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

22
src/app/shared/components/ui/erasable-input/erasable-input.component.ts

@ -0,0 +1,22 @@
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-erasable-input',
templateUrl: './erasable-input.component.html',
styleUrls: ['./erasable-input.component.scss'],
})
export class ErasableInputComponent implements OnInit {
@Output() inputModelChange = new EventEmitter();
@Input() inputModel;
constructor() {}
ngOnInit(): void {}
eraseInput() {
//
this.inputModelChange.emit('');
// TODO focus on other element
}
}

4
src/app/shared/shared.module.ts

@ -23,6 +23,8 @@ import { LanguageSelectorComponent } from './components/selectors/language-selec
import { ThemeSelectorComponent } from './components/selectors/theme-selector/theme-selector.component';
import { SettingsComponent } from './components/settings/settings.component';
import { SpinnerComponent } from './components/spinner/spinner.component';
import { CopyTextComponent } from './components/ui/copy-text/copy-text.component';
import { ErasableInputComponent } from './components/ui/erasable-input/erasable-input.component';
const COMPONENTS = [
ChoiceDetailsComponent,
@ -33,6 +35,8 @@ const COMPONENTS = [
SettingsComponent,
SpinnerComponent,
ThemeSelectorComponent,
CopyTextComponent,
ErasableInputComponent,
];
const ANGULAR_MODULES = [CommonModule, ChartsModule, FormsModule, TranslateModule];

2
src/environments/environment.ts

@ -8,7 +8,7 @@ const backendApiUrlsInDev = {
};
const apiV1 = {
baseHref: 'https://framadate-api.cipherbliss.com/api/v1',
api_new_poll: '/poll/new',
api_new_poll: '/poll/',
api_get_poll: '/poll/{id}',
'api_test-mail-poll': '/api/v1/poll/mail/test-mail-poll/{emailChoice}',
'app.swagger': '/api/doc.json',

Loading…
Cancel
Save