setValue in formArray angular 8 and show ui - html

I want show initial data in my formArray
i can set value and show value in console log but dont show this data in the ui form
ngOnInit() {
this.getCertificate(this.id);
this.assessmentForm = this.fb.group({
certificateArray: this.fb.array([ this.createItem() ]),
});
}
createItem(): FormGroup {
return this.fb.group({
confirm: '',
score: '',
description: ''
});
}
getCertificate(id) {
this.certificateList = [];
this.UsersRegisterService.getCertificate(id).subscribe((res: any[]) => {
this.certificateList = res;
var index=0;
this.certificateList.forEach(element => {
this.AssessmentService.getCertificateAssessment(element.id.value).subscribe((res: any[]) => {
if(res!=null){
this.certificateArray.at(index).setValue(
{ confirm: res['confirm'], score: res['score']['value'],description:res['description']});
console.log( this.assessmentForm['controls'].certificateArray['controls'][index]['controls'].score.value);
}
});
index++;
});
});
}
i set value this method
this.certificateArray.at(index).setValue(
{ confirm: res['confirm'], score: res['score']})
please help me how can i show this value in the Ui form

Use patchValue
this.certificateArray.at(index).patchValue(res);
Note that you would never subscribe inside a subscription, and even less often (never never) subscribe in a forEach. pipe the data instead.

You can refactor your code a little bit, right now you have a shadowed name res. I would log responses from each call to getCertificateAssessment to make sure you're getting what you expect:
getCertificate(id) {
this.certificateList = []; // this should be set at the top of your component
this.UsersRegisterService.getCertificate(id).pipe(
catchError(err => {
console.log('get cert error', err);
return [];
})
).subscribe((list) => {
this.certificateList = list;
this.certificateList.forEach((element, i) => {
this.AssessmentService.getCertificateAssessment(element.id.value).pipe(
catchError(err => {
console.log('get assessment error', err);
return null;
})
).subscribe((res) => {
if (res) {
console.log('res', i, res); // be sure of response
this.certificateArray.at(i).setValue({
confirm: res.confirm,
score: res.score.value,
description: res.description
});
} else {
console.log('no res!');
}
});
});
});
}
Chris makes a good point about piping but I'm guessing these service calls are http requests so they complete just like a promise.
I also added catchError to catch errors with the service calls.
Plus you are having to make a call for each assessment which makes for a lot of calls. Maybe refactor your backend to make it 1 call?
If you refactored the endpoint for getCertficateAssessment to accept an array of values and return an array of responses, you could do this:
this.UsersRegisterService.getCertificate(id).pipe(
switchMap(list => this.AssessmentService.getCertificateAssessment(list.map(l => l.id.value)))
);
You would need to create an id for each assessment so you could assign them.

Related

My response from api is undefined on frontend

I got list of items from my database mySql and also button 'edit'.
When I clicked edit (by id) I want to see all fields filled by data.
But I only have in my console: undefined
If I tested my api by postman it works fine.
There is how I am getting list.
{
const id = this.actRoute.snapshot.paramMap.get('id');
this.studentApi.GetStudent(id).subscribe((res: any) => {
console.log(res.data);
this.subjectArray = res.data;
console.log(this.subjectArray);
this.studentForm = this.fb.group({
id: [res.id, [Validators.required]],
domain_id: [res.domain_id, [Validators.required]],
source: [res.source, [Validators.required]],
destination: [res.destination]
});
});
}
There is my api.service.ts
GetStudent(id): Observable<any> {
const API_URL = `${this.endpoint}/read-student/${id}`;
return this.http.get(API_URL, { headers: this.headers })
.pipe(
map((res: Response) => {
return res || {};
}),
catchError(this.errorMgmt)
);
}
And there is my route
studentRoute.get('/read-student/:id', (request, response) => {
const id = request.params.id;
con.query('SELECT * FROM students WHERE id = ?', id, (error, result) => {
if (error) throw error;
response.send(result);
});
});
There is response from 'postman'
[
{
"id": 5,
"domain_id": 2,
"source": "tester0700#test.pl",
"destination": "testw#test.pl"
}
]
It seems like the response is an array, containing an object.
In that case, there is no need to use res.data, as that would imply the returned observable, res has a property named data, and that you are trying to access the value within that property. You can simply assign res to the subjectArray property. I am pretty sure res would be defined.
this.studentApi.GetStudent(id).subscribe((res: any) => {
console.log(res);
this.subjectArray = res;
// handle the rest here.
});

Return json data from Function

I use a function for Fetch with below code :
var URL='...'
export function PostData(method,data){
fetch(URL+method,{
method:'POST',
body:JSON.stringify(data),
headers:{'Content-Type':'application/json'},
}).then(res => res.json())
.then(response => {
var ret=JSON.stringify(response)
return ret
})
.catch((error) => {
console.error(error)
})
}
and use it like below :
var retData=PostData('login/Authenticate',data)
retData is empty but in function ret has data
You PostData function does currently not return anything, so it is empty.
First step would be to add a return statement:
export function PostData(method,data){
return fetch(URL+method,{
method:'POST',
...
This will make your function return a value, but not just a simple value, but a promise! Promises are not the easiest to understand, but there is also a of people who tried to explain them
- https://developers.google.com/web/fundamentals/primers/promises
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Now how can you use the value anyway?
PostData('login/Authenticate',data)
.then(retData => {
// ... use retData here
});
Now, you used the react-native tag, so I am assuming you want to use this value in your render function. You can't do this simply by putting the PostData call in your render function. You'll have to put it in state, and then use that value in render:
state = { retData: null }
componentDidMount() {
PostData('login/Authenticate',data)
.then(retData => {
// This puts the data in the state after the request is done
this.setState({ retData: retData });
});
}
render() {
let retData = this.state.retData;
// ... use retData in your render here, will be `null` by default
There are a lot more different or cleaner ways to do this, but I tried to keep this answer as simple and bare as possible :)
It is empty at this point because the call to fetch is asynchronous and the literal is set to undefined as it moves to the next statement because it has not been resolved yet. One way around it is to return the promise object itself and then use .then to get the response once it is resolved.
var URL = '...'
export function PostData(method, data) {
// return the promise object
return fetch(URL + method, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
},
}).then(res => res.json())
.then(response => {
var ret = JSON.stringify(response)
return ret
})
.catch((error) => {
console.error(error)
})
}
PostData('login/Authenticate',data).then(response => {
// do something with the response
});
A cleaner approach would be is to use the async/await ES7 feature which makes it more readable.
var URL = '...'
export function PostData(method, data) {
// return the promise object
return fetch(URL + method, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
},
}).then(res => res.json())
.then(response => {
var ret = JSON.stringify(response)
return ret
})
.catch((error) => {
console.error(error)
})
}
async function getData() {
let retData = await PostData('login/Authenticate',data);
}

How to get data (of my api json) in my object ( Redux, React )?

I not undestand everything with javascript etc, I want to get my data returned by ma action redux but i'have a problem with my code.
const mapStateToProps = state => {
const group = state.groupReducer.group ? state.groupReducer.group : [ ]
return {
group
}
how i can get my data ?
When I try with that:
const mapStateToProps = state => {
const group = state.groupReducer.group.data.data[0] ? state.groupReducer.group.data.data[0] : [ ]
return {
group
}
And my goal is map around group
renderGroup = group => {
return group.map((groups => {
<div key={groups.data.data.id}>
//
</div>
}))
}
Sagas.js
export function* loadApiDataGroup() {
try {
// API
const response = yield
call(axios.get,'http://localhost:8000/api/group');
yield put(loadGroup(response))
} catch (e) {
console.log('REQUEST FAILED! Could not get group.')
console.log(e)
}
}
Action.js
export function loadGroup(data){ return { type: LOAD_GROUP, data }};
export function creatGroup(data){ return { type: CREATE_GROUP, data}};
// reducer
export default function groupReducer( state= {}, action = {}){
switch (action.type){
case LOAD_GROUP:
return {
...state,
group: action.data
}
case CREATE_GROUP:
return {
...state
}
default:
return state
}
thank you to help me
Try
const mapStateToProps = state => ({
group: state.groupReducer.group || []
});
Then you can use this.props.group in the component. Even though you might only want one thing in mapStateToProps, it's usually not directly returned like that.
If group is the response of an API request, you need to unpack data first, this is done in your async action creator (you will want to use redux-thunk or something similar):
const getGroup = () => async (dispatch) => {
dispatch({ type: 'GET_GROUP_REQUEST' });
try {
const { data } = await axios.get('/some/url');
dispatch({ type: 'GET_GROUP_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'GET_GROUP_FAILURE', payload: error });
}
};

TextDecoder failing in ES6 Promise recursion

I'm attempting to query an API which responds with a ReadableStream of XML.
The code below uses a recursive Promise. Recursive because it sometimes doesn't decode the stream in a singular iteration and this is whats causing my headache.
While I'm successfully fetching the data, for some reason the decoding stage doesn't complete sometimes, which leads me to believe it's when the stream is too large for a single iteration.
componentDidMount() {
fetch("http://thecatapi.com/api/images/get?format=xml&size=med&results_per_page=9")
.then((response) => {
console.log('fetch complete');
this.untangleCats(response);
})
.catch(error => {
this.state.somethingWrong = true;
console.error(error);
});
}
untangleCats({body}) {
let reader = body.getReader(),
string = "",
read;
reader.read().then(read = (result) => {
if(result.done) {
console.log('untangling complete'); // Sometimes not reaching here
this.herdingCats(string);
return;
}
string += new TextDecoder("utf-8").decode(result.value);
}).then(reader.read().then(read));
}
I think that the next iteration was sometimes being called before the current iteration had completed, leading to incorrectly concatenation of the decoded XML.
I converted the function from sync to async and as a regular recursive method of the component rather than a recursive promise with a method.
constructor({mode}) {
super();
this.state = {
mode,
string: "",
cats: [],
somethingWrong: false
};
}
componentDidMount() {
fetch("http://thecatapi.com/api/images/get?format=xml&size=med&results_per_page=9")
.then( response => this.untangleCats( response.body.getReader() ) )
.catch(error => {
this.setState({somethingWrong: true});
console.error(error);
});
}
async untangleCats(reader) {
const {value, done} = await reader.read();
if (done) {
this.herdingCats();
return;
}
this.setState({
string: this.state.string += new TextDecoder("utf-8").decode(value)
});
return this.untangleCats(reader);
}

How to execute promise of super class in ES6

I've a promise in Parent class, whenever I call the promise from child class, it is returning the undefined, instead of executing the promise and returning the resul.
import {newsApiKey as APIKEY, newUrl as APIURL} from "./secretToken";
class News{
constructor(){
this.token = APIKEY;
this.url = APIURL;
this.source = 'bbc-news&';
}
topNews(){
const bbcNews = fetch(`${this.url}?source=${this.source}&sortBy=top&apiKey=${this.token}`);
bbcNews.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json()
})
.then(json => {
console.log(json.articles);
return json.articles;
})
.catch((err) => {
return err.message;
});
}
}
export { News as default};
CHILD CLASS
import News from "./news";
class StickyNote extends News{
displayNews(){
let bbcNews = super.topNews(); // It is returning only undefined
if (typeof bbcNews != 'undefined') {
console.log(bbcNews); //
}
}
}
topNews never returns anything, so the result of calling it is undefined.
You probably wanted a return here:
topNews() {
const bbcNews = fetch(`${this.url}?source=${this.source}&sortBy=top&apiKey=${this.token}`);
return bbcNews.then(response => {
// ^^^^^^
if (!response.ok) {
throw Error(response.statusText);
}
return response.json()
})
.then(json => {
console.log(json.articles);
return json.articles;
})
.catch((err) => {
return err.message;
});
}
Also note that displayNews will need to use the promise it receives:
displayNews(){
super.topNews().then(articles => {
// ...use articles
});
}
(Normally you'd also have a catch there at the endpoint of consumption, but as you've converted rejections into resolutions...)
Note: That code has a bit of an anti-pattern in it: It converts a rejection into a resolution with an error message. Anything using the promise will never see a rejection, only resolutions with varying return types (whatever json.articles is or a string). In general, it's better to allow rejections to propagate, and handle them at the ultimate point of consumption of the entire chain (displayNews, I believe, in your example). You might transform their content, but not convert them from a rejection into a resolution.
FWIW, I'd probably rewrite that like so:
topNews() {
return fetch(`${this.url}?source=${this.source}&sortBy=top&apiKey=${this.token}`)
.catch(_ => {
throw new Error("network error");
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(data => { // "data", not "json" -- it's not JSON anymore
return data.articles;
});
}
...which ensures that the caller either gets a resolution with the articles, or a rejection with an Error, so:
displayNews(){
super.topNews()
.then(articles => {
// ...use articles
})
.catch(err => {
// ...show error
});
}