npm install stockings-client
Minimal configuration:
import { StockingsClient } from 'stockings-client'
let client = new StockingsClient() // connects to the host and port of the current URL
Specifying port:
import { StockingsClient } from 'stockings-client'
let client = new StockingsClient(3000) // connects to the host of the current URL at the specified port
Specifying host and port:
import { StockingsClient } from 'stockings-client'
let client = new StockingsClient('ws://localhost:3000') // connects to the given host and port
Advanced configuraiton with port and/or host:
import { StockingsClient, SocketConnection } from 'stockings-client'
let client = new StockingsClient({
socketEndpoint: 'ws://localhost:3000', // specify host:port or just port
waitUntilToken: false // don't wait until the token is recieved before making any requests
})
Advanced configuraiton with socket connection:
import { StockingsClient, SocketConnection } from 'stockings-client'
let connection = new SocketConnection('ws://localhost:3000') // only accepts full host:port
let client = new StockingsClient({
socket: connection, // specify your own connection
waitUntilToken: false // don't wait until the token is recieved before making any requests
})
Minimal GET request:
function setUser(user) {
// do something
}
let subscription = client.request('/api/user/123').subscribe(setUser)
Using another HTTP method:
let subscription = client.request({
url: '/api/user',
method: 'POST',
body: user
}).subscribe()
Advanced request:
import { HttpHeadersFromDictionary }
let subscription = client.request({
url: '/api/user',
method: 'GET',
search: 'skip=10&limit=5',
headers: {
auth: jwt
},
responseType: 'blob'
}).subscribe(usersBlob => {
// do something
})
subscription.unsubscribe()
Unsubscribing automatically stops listening for any socket events associated with the request, unless it is also used by another open request subscription.
Setup within module:
@NgModule({
// ...
providers: [
// ...
{ provide: StockingsClient, useValue: client }
],
// ...
})
export class AppModule { }
Usage within a component
@Component({
selector: 'app-user',
template: `
<div *ngIf="user">
<img [src]="user.avatarurl" />
{{ user.username }}
</div>
`
})
export class UserComponent implements OnInit, OnDestroy {
@Input() userId: number
private user$: Subscription
user: User
error: any
constructor(private client: StockingsClient) {}
ngOnInit() {
this.user$ = this.client
.request<User>(`/api/user/${this.userId}`)
.subscribe(
user => this.user = user,
error => this.error = error
)
}
ngOnDestroy() {
this.user$.unsubscribe()
}
}