Angular 2 to latest - jsonp and URLSearchParams to HttpClient and HttpParams - javascript

I am trying to upgrade this to latest but getting error to display the data. i need to refactor from Jsonp to HttpClient, and HttpParams for below code. Any help would be great.
import { Injectable } from '#angular/core';
import {Jsonp, URLSearchParams} from '#angular/http';
import 'rxjs/Rx';
#Injectable()
export class MyService {
apikey: string;
constructor(private _jsonp: Jsonp) {
this.apikey = 'my_api_key';
console.log('it works');
}
getData() {
var search = new URLSearchParams();
search.set('sort_by','popularity.desc');
search.set('api_key', this.apikey);
return this._jsonp.get('url', {search})
.map(res => {
return res.json();
})
}
}

This should be able to fix your problem. Please check doc for more info
In you module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
In your service
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable()
export class MyService {
apikey: string;
constructor(private http: HttpClient){
this.apikey = 'my_api_key';
}
getData(): Observable<any> {
const params = new HttpParams()
.set('sort_by', popularity.desc)
.set('api_key', this.apikey);
return this.http.get('url', {params});
}
}

Related

Use HTML Link in InnerHTML to display that file in Angular

I want to display the links that are stored in a json file like this:
[
{
"heading": "Waswas",
"content": "./waswas.html"
},
{
"heading": "Flu",
"content":""
}
]
In my component.ts file I parse that to an array variable like this:
public treatmentsList:{heading: string, content: string}[] = treatments;
Then in my component.html file I have this:
<div>
<h1>
{{treatmentsList[0].heading}}
</h1>
<span [innerHTML]="getContent(treatmentsList[0].content) | async"></span>
</div>
But it shows the link instead of the file
The component.ts file:
import { Content } from '#angular/compiler/src/render3/r3_ast';
import { Component, NgModule, OnInit } from '#angular/core';
import { SafeHtml } from '#angular/platform-browser';
import { Observable } from 'rxjs';
import { ContentService } from '../content.service';
import treatments from "./treatments.json"
var heading = "hTempl"
#Component({
selector: 'app-treatment',
templateUrl: './treatment.component.html',
styleUrls: ['./treatment.component.css']
})
export class TreatmentComponent implements OnInit {
public treatmentsList:{heading: string, content: string}[] = treatments;
constructor(
private readonly contentService: ContentService
) {}
public getContent(path: string): Observable<SafeHtml> {
return this.contentService.get(path);
}
ngOnInit(): void {
}
}
app.module.ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TreatmentComponent } from './treatment/treatment.component';
import { PrgrefComponent } from './prgref/prgref.component';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
TreatmentComponent,
PrgrefComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Create a service to fetch your html documents and then sanitize them.
content.service.ts
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { DomSanitizer, SafeHtml } from '#angular/platform-browser';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
#Injectable({
providedIn: 'root',
})
export class ContentService {
constructor(
private readonly http: HttpClient,
private readonly sanitizer: DomSanitizer
) {}
public get(path: string): Observable<SafeHtml> {
const headers = new HttpHeaders({
'Content-Type': 'text/plain',
});
return this.http.get(path, {
headers,
responseType: 'text'
}).pipe(
// This is unsafe if the path and content is not under your control
map(html => this.sanitizer.bypassSecurityTrustHtml(html))
);
}
}
Then in your component.ts use the service
constructor(
private readonly contentService: ContentService
)
public getContent(path: string): Observable<SafeHtml> {
return this.contentService.get(path);
}
Finally your html
<span [InnerHTML]="getContent(treatmentsList[0].content) | async"></span>

Can't bind to 'appIfRoles' since it isn't a known property of 'p'

I wanted to implement View Component Based On User Role In Angular 10 , to hide and show component. But I am block with the error above. Does anyone here has an idea about the issue? Help and idea would be much appreciated. Thanks.
#Role service code
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { Observable } from "rxjs";
/**
* The Role Service service
*/
#Injectable()
export class RolesService {
private rolesAPi: string = "https://api.npoint.io/97c436983e2fbacffc7f";
constructor(private http: HttpClient) {}
/**
* gets the user role
*/
public roles(): Observable<{ roles: string[] }> {
return this.http.get<{ roles: string[] }>(this.rolesAPi);
}
}
component.html code
<p *appIfRoles='["Admin"]'>
ADMIN CONTENT IS VIEWED
</p>
if-roles.directive.ts directive code
import { Input, OnInit, Directive, ViewContainerRef, TemplateRef, OnDestroy } from "#angular/core";
import { Subject, Subscription } from "rxjs";
import { takeUntil } from "rxjs/operators";
import { RolesService } from "../../core/services/user-role.service"
#Directive({
selector: '[appIfRoles]'
})
export class IfRolesDirective implements OnInit, OnDestroy {
private subscription: Subscription[] = [];
// the role the user must have
#Input() public ifRoles: Array<string>;
/**
* #param {ViewContainerRef} viewContainerRef -- the location where we need to render the templateRef
* #param {TemplateRef<any>} templateRef -- the templateRef to be potentially rendered
* #param {RolesService} rolesService -- will give us access to the roles a user has
*/
constructor(
private viewContainerRef: ViewContainerRef,
private templateRef: TemplateRef<any>,
private rolesService: RolesService
) {}
public ngOnInit(): void {
this.subscription.push(
this.rolesService.roles().subscribe(res => {
if (!res.roles) {
// Remove element from DOM
this.viewContainerRef.clear();
}
// user Role are checked by a Roles mention in DOM
const idx = res.roles.findIndex((element) => this.ifRoles.indexOf(element) !== -1);
if (idx < 0) {
this.viewContainerRef.clear();
} else {
// appends the ref element to DOM
this.viewContainerRef.createEmbeddedView(this.templateRef);
}
})
);
}
/**
* on destroy cancels the API if its fetching.
*/
public ngOnDestroy(): void {
this.subscription.forEach((subscription: Subscription) => subscription.unsubscribe());
}
}
app.module.ts code
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { RouterModule } from '#angular/router';
import { LoginComponent } from './core/pages/login/login.component';
import { DashboardComponent } from './core/pages/dashboard/dashboard.component';
import { LayoutModule } from '#angular/cdk/layout';
import { SideNavComponent } from './core/components/side-nav/side-nav.component';
import { HeaderBarComponent } from './core/components/header-bar/header-bar.component';
import { UserprofileComponent } from './core/components/userprofile/userprofile.component';
import { UserInviteFormDialogComponent } from './core/components/user-invite-form-dialog/user-invite-form-dialog.component';
import { HeaderInterceptor } from './core/interceptors/header.interceptor';
import { RolesService } from './core/services/user-role.service';
import { SharedModule } from './shared/shared.module';
//import { AgmCoreModule } from '#agm/core';
import { ToastrModule } from 'ngx-toastr';
import { NgxMaskModule, IConfig } from 'ngx-mask';
import { IfRolesDirective } from './shared/directives/if-roles.directive';
// import { CoreModule } from './core/core.module';
const ngMaskConfig: Partial<IConfig> = {
validation: false,
};
#NgModule({
declarations: [
AppComponent,
IfRolesDirective,
LoginComponent,
DashboardComponent,
SideNavComponent,
HeaderBarComponent,
UserprofileComponent,
UserInviteFormDialogComponent,
,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
LayoutModule,
RouterModule,
HttpClientModule,
// CoreModule,
ToastrModule.forRoot({
preventDuplicates: true,
enableHtml: true,
progressBar: true
}),
SharedModule,
NgxMaskModule.forRoot(ngMaskConfig),
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: HeaderInterceptor,
multi: true,},
RolesService,],
bootstrap: [AppComponent]
})
export class AppModule { }
You're almost there! Just missing the export in app.module.ts
#NgModule({
declarations: [
...
IfRolesDirective,
...],
imports: [...],
exports: [IfRolesDirective]
providers: [...],
})
Try the following code.
<p *ifRoles='["Admin"]'>
ADMIN CONTENT IS VIEWED
</p>
#Directive({
selector: '[ifRoles]'
})
export class IfRolesDirective implements OnInit, OnDestroy {
private subscription: Subscription[] = [];
// the role the user must have
#Input() public ifRoles: Array<string>;
....
....
}

Service not found in NativeScript Angular

I am new to Angular nativescript, I created a service using the "ng generate service" command in my native angular application, but when importing the service I get the error that the module cannot be found
app.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptModule, NativeScriptHttpClientModule } from "#nativescript/angular";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { LoginComponent } from './components/login/login.component';
#NgModule({
bootstrap: [
AppComponent
],
imports: [
NativeScriptModule,
AppRoutingModule,
NativeScriptHttpClientModule
],
declarations: [
AppComponent,
LoginComponent,
],
providers: [],
schemas: [
NO_ERRORS_SCHEMA
]
})
/*
Pass your application module to the bootstrapModule function located in main.ts to start your app
*/
export class AppModule { }
ApiBackRequestService.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { environment } from '../environments/environment';
#Injectable({
providedIn: 'root'
})
export class ApiBackRequestService {
constructor(
private http: HttpClient) {
}
}
Login.component.ts
import { Component, OnInit } from '#angular/core';
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
#Component({
selector: 'ns-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
pokemon = [];
constructor(private api: ApiBackRequestService) { }
ngOnInit(): void {
}
}
Thanks
Is it a code-sharing project? in the Login.component.ts file just add # before the src.
change
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
to
import { ApiBackRequestService } from '#src/app/services/api-back-request.service';
this solved my problem
import { ApiBackRequestService } from '../../services/api-back-request.service';

Angular 4.3.3 : Why can't I get a DI in the Service

Before I ask, I do not speak English very well.
first, I'm #angular#4.3.3 and my typescript version is ~2.3.3
Ask.
I lazy loaded the LoginModule
AppRoute
import { RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login#LoginModule' }
];
export const AppRoutes = RouterModule.forRoot(routes);
and my
AppModule
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { AppRoutes } from './routing/app.routing';
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutes,
],
providers: [
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
and
LoginModule
import { CommonModule } from '#angular/common';
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { ErrorCodeService } from '../shared/service/error-code/error-code.service';
import { LoginService } from '../shared/service/login/login.service';
import { LoginComponent } from './login.component';
#NgModule({
imports: [
HttpClientModule,
CommonModule,
FormsModule,
RouterModule.forChild([
{ path: '', component: LoginComponent }
])
],
exports: [],
declarations: [ LoginComponent ],
providers: [
ErrorCodeService,
LoginService,
],
})
export class LoginModule { }
and
LoginService
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorCodeService } from '../error-code/error-code.service';
import { RequestCore } from '../request-core';
#Injectable()
export class LoginService extends RequestCore {
constructor(
protected http: HttpClient,
private errorCode: ErrorCodeService,
) {
super(http, '/Login');
}
public load(userid: string, passwd: string): Observable<any> {
const params = new HttpParams()
.append('id', userid)
.append('passwd', passwd);
return this.get({ params })
.map(res => {
if (res.islogin === 'true') {
return res.sendRedirect;
}
throw new Error(this.errorCode.getErrorMsg(res.reason));
});
}
}
RequestCore
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../../environments/environment';
import { HttpOptions } from '../models';
export abstract class RequestCore {
constructor(
protected http: HttpClient,
private url: string,
) {
// 개발 모드에서는 proxy를 위해 url에 /dev 접두어를 붙인다.
if (environment.production === false) {
url = '/dev' + url;
}
}
protected get(options?: HttpOptions): Observable<any> {
return this.http.get(this.url, options);
}
protected post(options?: HttpOptions): Observable<any> {
return this.http.post(this.url, {}, options);
}
}
This is my error
I don't know why I can't DI in LoginService
ReuquestCore Are you making the wrong inheritance?
Teach me
Thank you!
Re:
An error occurs when the first screen is loaded.
When the next hmr is updated, no error occurs.

HTTP service not working

This is my HttpService.ts
import { Injectable } from "#angular/core";
import { Http, Response } from "#angular/http";
import 'rxjs/add/operator/map';
#Injectable()
export class HttpService {
constructor (private http: Http) {}
getData() {
return this.http.get('http://blog_api.org/v1/posts')
.map((response: Response) => response.json());
}
}
This is my app.component.ts
import { Component } from '#angular/core';
import { HttpService } from '../app/services/HttpService'
#Component({
selector: 'my-app',
template: `Hello`,
})
export class AppComponent {
constructor (private httpService: HttpService) {};
ngOnInit() {
this.httpService.getData()
.subscribe(
data => console.log(data)
)
}
}
When I running app, I get error:
EXCEPTION: No provider for HttpService!
In your AppModule you should be doing:
import {HttpService} from "...";
import {HttpModule} from "#angular/http";
#NgModule({
bootstrap: [...],
imports: [HttpModule],
declarations: [...],
entryComponents: [...],
providers: [HttpService]
})
export default class AppModule{}
You must provide the HttpService in the model that loads the app.component.ts.
In your case, as you are using app.component.ts, provide the http in app.module.ts. Something like:
import { HttpService } from '../app/services/HttpService'
#NgModule({
...
providers: [
...
HttpService,
]
})
export class AppModule { }
Add
providers: [HttpService]
in #Component block

Categories

Resources