Skip to content

Commit

Permalink
Promise -> Observable
Browse files Browse the repository at this point in the history
  • Loading branch information
autowp committed Jun 16, 2018
1 parent 4ca1cb3 commit 234aad2
Show file tree
Hide file tree
Showing 32 changed files with 696 additions and 824 deletions.
133 changes: 67 additions & 66 deletions ng2/src/app/about/about.component.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { Component, Injectable } from '@angular/core';
import { Component, Injectable, OnInit, OnDestroy } from '@angular/core';
import * as showdown from 'showdown';
import * as escapeRegExp from 'lodash.escaperegexp';
import { UserService, APIUser } from '../services/user';
import { HttpClient } from '@angular/common/http';
import Notify from '../notify';
import { TranslateService } from '@ngx-translate/core';
import { Router } from '@angular/router';
import { DecimalPipe } from '@angular/common';
import { BytesPipe } from 'ngx-pipes';
import { PageEnvService } from '../services/page-env.service';
import { combineLatest, Subscription } from 'rxjs';
import { switchMap } from 'rxjs/operators';

export class APIAbout {
developer: number;
Expand Down Expand Up @@ -42,8 +43,9 @@ function replacePairs(str: string, pairs: { [key: string]: string }): string {
templateUrl: './about.component.html'
})
@Injectable()
export class AboutComponent {
export class AboutComponent implements OnInit, OnDestroy {
public html = '';
private sub: Subscription;

constructor(
private http: HttpClient,
Expand All @@ -53,7 +55,9 @@ export class AboutComponent {
private decimalPipe: DecimalPipe,
private bytesPipe: BytesPipe,
private pageEnv: PageEnvService
) {
) {}

ngOnInit(): void {
setTimeout(
() =>
this.pageEnv.set({
Expand All @@ -66,70 +70,67 @@ export class AboutComponent {
0
);

this.http.get<APIAbout>('/api/about').subscribe(
response => {
this.translate.get('about/text').subscribe(
translation => {
const ids: number[] = response.contributors;
ids.push(response.developer);
ids.push(response.fr_translator);
ids.push(response.zh_translator);
ids.push(response.be_translator);
ids.push(response.pt_br_translator);

this.userService.getUserMap(ids).then(
(users: Map<number, APIUser>) => {
const contributorsHtml: string[] = [];
for (const id of response.contributors) {
contributorsHtml.push(this.userHtml(users.get(id)));
}
this.sub = combineLatest(
this.http.get<APIAbout>('/api/about'),
this.translate.get('about/text')
)
.pipe(
switchMap(
data => {
const ids: number[] = data[0].contributors;
ids.push(data[0].developer);
ids.push(data[0].fr_translator);
ids.push(data[0].zh_translator);
ids.push(data[0].be_translator);
ids.push(data[0].pt_br_translator);

const markdownConverter = new showdown.Converter({});
this.html = replacePairs(
markdownConverter.makeHtml(translation),
{
'%users%': contributorsHtml.join(' '),
'%total-pictures%': this.decimalPipe.transform(
response.total_pictures
),
'%total-vehicles%': response.total_cars.toString(),
'%total-size%': bytesPipe
.transform(response.pictures_size, 1)
.toString(),
'%total-users%': response.total_users.toString(),
'%total-comments%': response.total_comments.toString(),
'%github%':
'<i class="fa fa-github"></i> <a href="https://github.com/autowp/autowp">https://github.com/autowp/autowp</a>',
'%developer%': this.userHtml(users.get(response.developer)),
'%fr-translator%': this.userHtml(
users.get(response.fr_translator)
),
'%zh-translator%': this.userHtml(
users.get(response.zh_translator)
),
'%be-translator%': this.userHtml(
users.get(response.be_translator)
),
'%pt-br-translator%': this.userHtml(
users.get(response.pt_br_translator)
)
}
);
},
responses => {
console.log('reject', responses);
}
);
return this.userService.getUserMap(ids);
},
responses => {
console.log('Failed to translate');
}
);
},
response => {
Notify.response(response);
}
);
(data, users) => ({
users: users,
translation: data[1],
about: data[0]
})
)
)
.subscribe(data => {
const contributorsHtml: string[] = [];
for (const id of data.about.contributors) {
contributorsHtml.push(this.userHtml(data.users.get(id)));
}

const markdownConverter = new showdown.Converter({});
this.html = replacePairs(markdownConverter.makeHtml(data.translation), {
'%users%': contributorsHtml.join(' '),
'%total-pictures%': this.decimalPipe.transform(
data.about.total_pictures
),
'%total-vehicles%': data.about.total_cars.toString(),
'%total-size%': this.bytesPipe
.transform(data.about.pictures_size, 1)
.toString(),
'%total-users%': data.about.total_users.toString(),
'%total-comments%': data.about.total_comments.toString(),
'%github%':
'<i class="fa fa-github"></i> <a href="https://github.com/autowp/autowp">https://github.com/autowp/autowp</a>',
'%developer%': this.userHtml(data.users.get(data.about.developer)),
'%fr-translator%': this.userHtml(
data.users.get(data.about.fr_translator)
),
'%zh-translator%': this.userHtml(
data.users.get(data.about.zh_translator)
),
'%be-translator%': this.userHtml(
data.users.get(data.about.be_translator)
),
'%pt-br-translator%': this.userHtml(
data.users.get(data.about.pt_br_translator)
)
});
});
}
ngOnDestroy(): void {
this.sub.unsubscribe();
}

private userHtml(user: APIUser): string {
Expand Down
4 changes: 2 additions & 2 deletions ng2/src/app/account/sidebar/sidebar.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class AccountSidebarComponent implements OnInit, OnDestroy {
private pageService: PageService,
private auth: AuthService,
private pictureService: PictureService
) { }
) {}

ngOnInit(): void {
this.sub = combineLatest(
Expand Down Expand Up @@ -165,7 +165,7 @@ export class AccountSidebarComponent implements OnInit, OnDestroy {

for (const item of this.items) {
if (item.pageId) {
this.pageService.isActive(item.pageId).then(
this.pageService.isActive(item.pageId).subscribe(
active => {
item.active = active;
},
Expand Down
63 changes: 36 additions & 27 deletions ng2/src/app/account/specs-conflicts/specs-conflicts.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ import {
APIAttrConflictValue
} from '../../services/attrs';
import { PageEnvService } from '../../services/page-env.service';
import { distinctUntilChanged, debounceTime, tap, switchMap, switchMapTo } from 'rxjs/operators';
import {
distinctUntilChanged,
debounceTime,
tap,
switchMap,
switchMapTo
} from 'rxjs/operators';

interface APIAttrConflictValueInList extends APIAttrConflictValue {
user?: APIUser;
Expand Down Expand Up @@ -41,7 +47,7 @@ export class AccountSpecsConflictsComponent implements OnInit, OnDestroy {
private route: ActivatedRoute,
private attrService: AttrsService,
private pageEnv: PageEnvService
) { }
) {}

ngOnInit(): void {
this.pageEnv.set({
Expand All @@ -53,41 +59,44 @@ export class AccountSpecsConflictsComponent implements OnInit, OnDestroy {
});

this.querySub = combineLatest(
this.route.queryParams
.pipe(
distinctUntilChanged(),
debounceTime(30)
),
this.route.queryParams.pipe(
distinctUntilChanged(),
debounceTime(30)
),
this.auth.getUser().pipe(
switchMapTo(this.http.get<APIUser>('/api/user/me', {
params: { fields: 'specs_weight' }
}))
switchMapTo(
this.http.get<APIUser>('/api/user/me', {
params: { fields: 'specs_weight' }
})
)
),
(params, user) => ({ params, user })
).pipe(
tap(data => {
this.filter = data.params.filter || '0';
this.page = data.params.page;
this.user = data.user;
}),
switchMap(data => this.attrService
.getConfilicts({
filter: data.params.filter || '0',
page: data.params.page,
fields: 'values'
)
.pipe(
tap(data => {
this.filter = data.params.filter || '0';
this.page = data.params.page;
this.user = data.user;
}),
(data, conflicts) => ({
user: data.user,
conflicts: conflicts
})
switchMap(
data =>
this.attrService.getConfilicts({
filter: data.params.filter || '0',
page: data.params.page,
fields: 'values'
}),
(data, conflicts) => ({
user: data.user,
conflicts: conflicts
})
)
)
)
.subscribe(data => {
this.conflicts = data.conflicts.items;
for (const conflict of this.conflicts) {
for (const value of conflict.values) {
if (data.user.id !== value.user_id) {
this.userService.getUser(value.user_id, {}).then(user => {
this.userService.getUser(value.user_id, {}).subscribe(user => {
value.user = user;
});
}
Expand Down
6 changes: 3 additions & 3 deletions ng2/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export class AppComponent implements OnInit {

this.layoutParams$ = this.pageEnv.layoutParams$.asObservable();

this.auth.loadMe();
this.auth.loadMe().subscribe();

this.auth.getUser().subscribe(user => {
this.user = user;
Expand Down Expand Up @@ -86,7 +86,7 @@ export class AppComponent implements OnInit {
this.loginForm.password,
this.loginForm.remember
)
.then(
.subscribe(
() => {
this.router.navigate(['/login/ok']);
},
Expand All @@ -103,7 +103,7 @@ export class AppComponent implements OnInit {
signOut(event) {
event.preventDefault();

this.auth.signOut().then(
this.auth.signOut().subscribe(
() => {},
error => {
console.log(error);
Expand Down
26 changes: 10 additions & 16 deletions ng2/src/app/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,21 @@
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';
import { AuthService } from './services/auth.service';
import { map } from 'rxjs/operators';

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private authService: AuthService, private router: Router) {}
constructor(private authService: AuthService) {}

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {


return new Promise<boolean>((resolve, reject) => {
this.authService.getUser().subscribe(user => {
resolve(!!user);
}, (error) => {
console.log(error);
resolve(false);
});
});
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.getUser().pipe(map(user => !!user));
}

}
4 changes: 2 additions & 2 deletions ng2/src/app/components/breadcrumbs/breadcrumbs.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy {
) {}

ngOnInit(): void {
this.sub = this.pageEnv.pageID$.subscribe((pageID) => {
this.sub = this.pageEnv.pageID$.subscribe(pageID => {
this.load(pageID);
});
}
Expand All @@ -46,7 +46,7 @@ export class BreadcrumbsComponent implements OnInit, OnDestroy {
this.items = [];
if (pageID) {
const args = this.pageService.getCurrentArgs();
this.pageService.getPath(pageID).then(path => {
this.pageService.getPath(pageID).subscribe(path => {
this.items = [];
for (const item of path) {
const bItem: APIPageInBreadcrumbs = item;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class ModalMessageComponent implements OnInit {
this.sending = true;
this.sent = false;

this.messageService.send(this.userId, this.text).then(
this.messageService.send(this.userId, this.text).subscribe(
() => {
this.sending = false;
this.sent = true;
Expand Down
2 changes: 1 addition & 1 deletion ng2/src/app/components/thumbnail/thumbnail.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class ThumbnailComponent implements OnInit, OnDestroy {
this.picture.perspective_item.item_id,
this.picture.perspective_item.type,
this.picture.perspective_item.perspective_id
);
).subscribe();
}
}

Expand Down
2 changes: 1 addition & 1 deletion ng2/src/app/donate/log/log.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class DonateLogComponent {

for (const item of this.items) {
if (item.user_id) {
this.userService.getUser(item.user_id, {}).then(user => {
this.userService.getUser(item.user_id, {}).subscribe(user => {
item.user = user;
});
}
Expand Down
Loading

0 comments on commit 234aad2

Please sign in to comment.