React/Typescript how do to load images? - image

I have a question about loading images into the reaction project. I use typescript and pass objects to the Table1 component as props. Some properties include the directories to load the images. My directories are in the public folder. The images are not loading and I don't know why.
This is the App:
//MY APP function
import React from 'react';
import './App.css';
import { Table1 } from './components/Table1';
import {Data} from './models/Data';
export const App = () => {
const data:Data[] = [
new Data("Gustav23", **"../public/images/typicalUser.png"**, 2), //I M A G E P A T H
new Data("Lex12", **../public/images/choice.png", 0),
new Data("Max&1", **"../public/images/customer.png", 30)
]
return (
<div className="App">
<Table1 data={data}/>
</div>
);
}
This is t´my Component:
import React from 'react';
import { Data } from '../models/Data';
export const Table1 : React.FC<{data: Data[]}>= (props)=>{
return (
<div>
<table>
<thead>
<tr>
<th scope="row">Username</th>
<th scope="row">Picture</th>
<th scope="row">Posts</th>
</tr>
</thead>
<tbody>
{props.data.map(dat =>(
<tr>
<td>{dat.nick}</td>
<td><img
src={dat.img}
width="150"
height= "210"
alt = "UserIcon"
/>
</td>
<td>{dat.count}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
And last my Model:
export class Data{
constructor(private _nick:string, private _img:string, private _count:number, ){
}
getNick():string{
return this._nick;
}
getImg():string{
return this._img;
}
setNick(value:string): void{
this._nick = value;
}
setImg(value:string):void{
this._img= value;
}
getCount():number{
return this._count;
}
setCount(value:number):void{
this._count = value;
}
get nick(){
return this._nick;
}
get img(){
return this._img;
}
get count(){
return this._count;
}
//------------------
set nick(value:string){
this._nick = value;
}
set img(value:string){
this._img = value;
}
set count(value:number){
this._count= value;
}
}
i tried to use require()-Method, my images were in src/images/ folder.
I want my pictures to be displayed.

Related

TokenProvider.RequestAccessToken() does not bring token AuthenticationState has idp_access_token, session cookie "credentialType": "IdToken" exists

I have a Blazor web assembly app authenticated by AD. The call to await TokenProvider.RequestAccessToken() does not bring the access token even though it is in the session storage and can be retrieved from the AuthenticationState as shown in the code below. Why is the tokenResult.Status shows "RequiresRedirect" and has no token value?
#page "/"
#using System.Security.Claims;
#using Microsoft.AspNetCore.Components.WebAssembly.Authentication
<PageTitle>Index</PageTitle>
<AuthorizeView>
<Authorized>
<table width="90%">
<tr>
<th style="width: 200px;">Claim Type</th>
<th>Claim Value</th>
</tr>
#foreach (var claim in User.Claims)
{
<tr>
<td>#claim.Type.ToString()</td>
<td class="tdValue">#claim.Value</td>
</tr>
}
</table>
<p>#idp_access_token?.Value</p>
</Authorized>
</AuthorizeView>
#code {
[Inject] IAccessTokenProvider TokenProvider { get; set; }
[CascadingParameter]
private Task<AuthenticationState>? AuthenticationStateTask { get; set; }
private ClaimsPrincipal User;
private AccessToken idp_access_token;
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateTask;
if (authState.User.Identity is { IsAuthenticated: true })
{
User = authState.User;
}
var tokenResult = await TokenProvider.RequestAccessToken();
//at this point tokenResult.Status has value of "RequiresRedirect" and the token is null
if (tokenResult.TryGetToken(out var token))
{
idp_access_token = token;
}
}
}
[UPDATE]
I managed to resolve the problem by adding in the program.cs class options.ProviderOptions.LoginMode = "Redirect" like this:
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("....");
options.ProviderOptions.LoginMode = "Redirect";
});

Angular Material Table sort behaving resulting in incorrect order

Im probably being stupid but as far as i can tell, below code should follow examples from angular material website exactly. however, the sorting result is incorrect.
I can see sorting happened because order changed. row xxx50 became the first row. row xxx01 moved to original position of xxx50. the rest of the data in original order. asc and des result in same order.
Please show me what im doing wrong.
html:
<div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="agent">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Agent</th>
<td mat-cell *matCellDef="let relationshipInterface"> {{relationshipInterface.agentDisplayName}} </td>
</ng-container>
<ng-container matColumnDef="player">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Player</th>
<td mat-cell *matCellDef="let relationshipInterface"> {{relationshipInterface.playerDisplayName}} </td>
</ng-container>
<ng-container matColumnDef="avatar">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Nickname</th>
<td mat-cell *matCellDef="let relationshipInterface"> {{relationshipInterface.avatarDisplayName}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;">
</tr>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>
ts:
import { Component, OnInit, ViewChild } from '#angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '#angular/material';
export interface RelationshipInterface {
agentName: string;
agentDisplayName: string;
playerName: string;
playerDisplayName: string;
avatarName: string;
avatarDisplayName: string;
}
#Component({
selector: 'app-relationships-table',
templateUrl: './relationships-table.component.html',
styleUrls: ['./relationships-table.component.css']
})
export class RelationshipsTableComponent implements OnInit {
displayedColumns: string[] = ['agent', 'player', 'avatar'];
dataSource: MatTableDataSource<RelationshipInterface>;
#ViewChild(MatPaginator) paginator: MatPaginator;
#ViewChild(MatSort) sort: MatSort;
constructor() {
}
ngOnInit() {
this.dataSource = new MatTableDataSource(
this.getTempData()
);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
applyFilter(filterColumn: string, filterValue: any) {
}
getTempData() {
const newData = [];
for (let i = 0; i < 100; i++) {
let str: string;
if (i < 10) {
str = '0' + i;
} else {
str = '' + i;
}
const relationshipInterface = {
agentName: 'agent name ' + str,
agentDisplayName: 'agent dName ' + str,
playerName: 'player name ' + str,
playerDisplayName: 'player dName ' + str,
avatarName: 'avatar name ' + str,
avatarDisplayName: 'avatar dName ' + str,
};
newData.push(relationshipInterface);
}
return newData;
}
}
after testing, apparently, column names must match data source property names.
i.e.
html:
<ng-container matColumnDef="agent">
ts:
export interface RelationshipInterface {
agent: string; // was agentDisplayName
}
Putting this out there since it is the first hit on Google. If anyone else comes across this issue;
My first problem was that some of the strings I was sorting had white spaces in the beginning of the string. This resulted in weird sorting being done.
The second problem was that MatSort is case sensitive (https://github.com/angular/components/issues/9205). This means it sorts large letters first, then small letters. The list AbCd will be sorted as ACbd.
Solution: Use the sortingDataAccessor to manipulate the data to be sorted before it is passed to the sort functionality. string.trim() removes white space characters in beginning and end of string. It can then be returned as string.toLowerCase() to ensure all data is sorted case insensitively.
Example:
#ViewChild(MatSort, { static: false }) set content(sort: MatSort) {
if (this.dataSource) {
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case 'description':
return this.cleanData(item.description);
case 'name':
return this.cleanData(item.name);
default:
return item[property] || '';
}
};
this.dataSource.sort = sort;
}
}
private cleanData(sortString: string): string {
let cleanString = '';
if (sortString) {
cleanString = sortString.trim();
}
return cleanString.toLowerCase();
}

What is the point of connect in React-redux?

I have this code:
import React, { Component } from 'react';
import { connect } from 'react-redux';
class WeatherList extends Component {
renderWeather(cityData) {
const name = cityData.city.name;
return (
<tr key={name}>
<td> {name} </td>
</tr>
)
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temp</th>
<th>Pressure</th>
<th>Humidity</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
)
}
}
function mapStateToProps({ weather }) { // es6 shorthand. it's as if state was teh argument and { weather: state.weather } was in the return
return { weather };
}
export default connect(mapStateToProps)(WeatherList);
On the last line, why can't I just write export default WeatherList? The state is available inside the component because of the mapStateToProps function right? So what is the point of the connect?
For more context, my reducer is this:
import { FETCH_WEATHER } from "../actions/index";
export default function(state = [], action) {
switch (action.type) {
case FETCH_WEATHER:
// return state.concat([ action.payload.data ]); // don't use push. concat creates a new array, while push mutates the old one. YOu want to create a new array, not mutate the old one.
return [ action.payload.data, ...state ];
}
return state;
}

Set state like this props in react

Hello i have this code
import React from 'react'
import Link from 'react-router/lib/Link'
import { connect } from "react-redux"
import { load } from '../../actions/customerActions'
import List from './list';
import MdAdd from 'react-icons/lib/md/add'
#connect(store => {
return {
customers: store.customer.customers
}
})
export default class Customer extends React.Component {
componentDidMount() {
this.props.dispatch(load({location:localStorage.getItem('locationb')}));
}
render() {
const { customers } = this.props;
const tea = customers.customers && customers.customers.map(customer => <List key={customer.profile} customer={customer} />) || [];
return(
<div class="container">
{ customers.customers ?
<div class="columns is-multiline mb-100">
{ tea }
</div>
: 'Não exitem Clientes'}
<Link to="/customer/create" class="button is-info btn-rounded" title="Novo"><MdAdd /></Link>
</div>
)
}
}
But i only have access to customers in render passing this props.
How can i pass customer to a state variable in component did mount or else ?
i mean customers const { customers } = this.props; how i make like this.setState({customers: customers}) Having in the beginning this.state(customers: [])
YOu can use
componentWillReceiveProps(newProps){
console.log(newProps.customers.customers)
this.setState({customers: newProps.customers.customers})
}
it works for me
thanks
Carlos Vieira

Error when running Jasmine tests for Angular 2 Component (angular2-seed)

I created a new Angular 2 project by cloning angular2-seed. I was able to create a SearchComponent and its associated template and got it work in my browser.
Here's my search.component.ts:
import {Component} from 'angular2/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/common';
import {ROUTER_DIRECTIVES, RouteParams} from 'angular2/router';
import {Person, SearchService} from '../../shared/services/search.service';
#Component({
selector: 'sd-search',
moduleId: module.id,
templateUrl: './search.component.html',
directives: [FORM_DIRECTIVES, CORE_DIRECTIVES, ROUTER_DIRECTIVES]
})
export class SearchComponent {
loading: boolean;
query: string;
searchResults: Array<Person>;
constructor(public searchService: SearchService, params: RouteParams) {
if (params.get('term')) {
this.query = decodeURIComponent(params.get('term'));
this.search();
}
}
search(): void {
this.searchService.search(this.query).subscribe(
data => {this.searchResults = data;},
error => console.log(error)
);
}
}
Here's my search.component.html:
<h2>Search</h2>
<form>
<input type="search" [(ngModel)]="query" (keyup.enter)="search()">
<button type="button" (click)="search()">Search</button>
</form>
<div *ngIf="loading">loading...</div>
<table *ngIf="searchResults">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr *ngFor="#person of searchResults; #i=index">
<td>{{person.name}}</td>
<td>{{person.phone}}</td>
<td>{{person.address.street}}<br/>
{{person.address.city}}, {{person.address.state}} {{person.address.zip}}
</td>
</tr>
</tbody>
</table>
Now I'm trying to create unit tests to verify this component works. As far as I can tell, angular2-seed requires you have an export main function() wrapped around the root describe. See https://github.com/mgechev/angular2-seed/blob/master/test-main.js#L50
Below is the search.component.spec.ts I'm trying to get working:
import {
it,
describe,
expect,
injectAsync,
beforeEachProviders,
TestComponentBuilder,
} from 'angular2/testing';
import {MockRouterProvider} from '../../shared/services/mocks/routes';
import {MockSearchService} from '../../shared/services/mocks/search.service';
import {SearchComponent} from './search.component';
export function main() {
describe('Search component', () => {
var mockSearchService:MockSearchService;
var mockRouterProvider:MockRouterProvider;
beforeEachProviders(() => {
mockSearchService = new MockSearchService();
mockRouterProvider = new MockRouterProvider();
return [
mockSearchService.getProviders(), mockRouterProvider.getProviders()
];
});
it('should search when a term is set and search() is called', injectAsync([TestComponentBuilder], (tcb) => {
return tcb.createAsync(SearchComponent).then((fixture) => {
let searchComponent = fixture.debugElement.children[0].componentInstance;
searchComponent.query = 'M';
searchComponent.search();
expect(mockSearchService.searchSpy).toHaveBeenCalledWith('M');
});
}));
it('should search automatically when a term is on the URL', injectAsync([TestComponentBuilder], (tcb) => {
mockRouterProvider.setRouteParam('term', 'peyton');
return tcb.createAsync(SearchComponent).then((fixture) => {
fixture.detectChanges();
expect(mockSearchService.searchSpy).toHaveBeenCalledWith('peyton');
});
}));
});
}
The Mock* classes are based on examples I found in ng-book2.
The strange thing is the error I see when I run npm test in my project.
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR: Error{stack: null, originalErr: ReferenceError{stack: '
eval code
eval#[native code]
__exec#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:1419:16
execute#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:3824:22
linkDynamicModule#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:3153:36
getModule#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:3121:26
http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:3157:25
require#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:3791:34
eval code
eval#[native code]
__exec#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:1419:16
execute#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:3824:22
linkDynamicModule#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:3153:36
link#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:2996:28
execute#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:3333:17
doDynamicExecute#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:727:32
link#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:929:36
doLink#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:581:11
updateLinkSetOnLoad#http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:629:24
http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef:441:30
run#http://localhost:9877/base/node_modules/zone.js/dist/zone-microtask.js?572d97c64312c5d52018e95b072a38b5443b057e:1217:29
zoneBoundFn#http://localhost:9877/base/node_modules/zone.js/dist/zone-microtask.js?572d97c64312c5d52018e95b072a38b5443b057e:1194:29
lib$es6$promise$$internal$$tryCatch#http://localhost:9877/base/node_modules/zone.js/dist/zone-microtask.js?572d97c64312c5d52018e95b072a38b5443b057e:442:25
lib$es6$promise$$internal$$invokeCallback#http://localhost:9877/base/node_modules/zone.js/dist/zone-microtask.js?572d97c64312c5d52018e95b072a38b5443b057e:454:53
lib$es6$promise$$internal$$publish#http://localhost:9877/base/node_modules/zone.js/dist/zone-microtask.js?572d97c64312c5d52018e95b072a38b5443b057e:425:53
http://localhost:9877/base/node_modules/zone.js/dist/zone-microtask.js?572d97c64312c5d52018e95b072a38b5443b057e:97:12
run#http://localhost:9877/base/node_modules/zone.js/dist/zone-microtask.js?572d97c64312c5d52018e95b072a38b5443b057e:1217:29
zoneBoundFn#http://localhost:9877/base/node_modules/zone.js/dist/zone-microtask.js?572d97c64312c5d52018e95b072a38b5443b057e:1194:29
lib$es6$promise$asap$$flush#http://localhost:9877/base/node_modules/zone.js/dist/zone-microtask.js?572d97c64312c5d52018e95b072a38b5443b057e:236:18', line: 9}, line: 752, sourceURL: 'http://localhost:9877/base/node_modules/systemjs/dist/system.src.js?4db5a6e7fcabd81638571091a65db6438de248ef'}
ERROR: Error{originalErr: ReferenceError{}}
Any idea what I'm doing wrong?
My MockSearchService was missing imports and a constructor to initialize spies. Changing it from:
export class MockSearchService extends SpyObject {
getAllSpy;
getByIdSpy;
searchSpy;
saveSpy;
mockObservable;
fakeResponse;
subscribe(callback) {
callback(this.fakeResponse);
}
setResponse(json: any): void {
this.fakeResponse = json;
}
getProviders(): Array<any> {
return [provide(SearchService, {useValue: this})];
}
}
to:
import {provide} from 'angular2/core';
import {SpyObject} from 'angular2/testing_internal';
import {SearchService} from '../search.service';
export class MockSearchService extends SpyObject {
getAllSpy;
getByIdSpy;
searchSpy;
saveSpy;
fakeResponse;
constructor() {
super(SearchService);
this.fakeResponse = null;
this.getAllSpy = this.spy('getAll').andReturn(this);
this.getByIdSpy = this.spy('get').andReturn(this);
this.searchSpy = this.spy('search').andReturn(this);
this.saveSpy = this.spy('save').andReturn(this);
}
subscribe(callback) {
callback(this.fakeResponse);
}
setResponse(json: any): void {
this.fakeResponse = json;
}
getProviders(): Array<any> {
return [provide(SearchService, {useValue: this})];
}
}
caused me to get proper error messages.

Resources