i use method setTimeout in my users.component.ts but does not work and get
cannot find module 'timers' error
i import this code but does not work
import { setTimeout } from 'timers'
I have used SetInterval function, Also remove the import statement that is autogenerated.
Ex :
import { Component, OnInit } from '#angular/core';
//import { setInterval } from 'timers';
export class HelloWorldComponent implements OnInit {
message : string ;
constructor() {
setInterval(() => {
let currentDate = new Date();
this.message = currentDate.toDateString() + " " + currentDate.toLocaleTimeString();
}, 1000);
}
ngOnInit() {
}
}
Whenever you are using the setTimeout in our code,import { setTimeout } from 'timers'
then this import we will get by autogenerating code, once remove this import statement and run the code it should work, for me working fine.
`
Do not import setTimeout from 'timers'.
It will work without any importing
Related
I am having a problem i can't seem to understand why is happening since i have the same example working in codesandbox, but in my app it shows a different behavior. In my app i can see the context from the consumer both the bool and the function, but when i run the function it runs the empty function "setUpdate: () => {}" instead of running the "updBool()" in UpdateDataProvider.js file. Anyone know why this behaviour happens.
(component.js is not my actual file just a short example of how im using the context)
UpdateDataProvider.js
export const UpdateDataContext = createContext({
update: false,
setUpdate: () => {},
});
export function UpdateDataContexProvider({ children }) {
function updBool(bool) {
setU({ ...u, update: bool });
}
const [u, setU] = useState({ update: false, setUpdate: updBool });
return (
<UpdateDataContext.Provider value={u}>
{children}
</UpdateDataContext.Provider>
);
}
useUpdateData.js
import { useContext } from 'react';
import { UpdateDataContext } from '../../context/updateDataContext';
export function useUpdateDataContext() {
return useContext(UpdateDataContext);
}
component.js
import { UpdateDataContexProvider } from '../../context/updateDataContext';
import { useUpdateDataContext } from '../../hooks/exports';
useEffect(() => {
// loging the context shows me update bool and setUpdate function
console.log(context)
// Running the function will run the empty function in createContext
// in UpdateDataProvider.
context.setUpdate(true)
}, [])
export default Home = () => {
const context = useUpdateDataContext()
return (
<UpdateDataContexProvider>
<Other />
</UpdateDataContexProvider>
)
}
Don't mind my question, the mistake was that i was trying to run the function in useEffect in the home component but not the childs
I'm using this npm library https://www.npmjs.com/package/ng-offline to alert end user when offline.
<div class="alert alert-danger" ngOffline>You're offline. Check your connection!</div>
stackblitz here: https://stackblitz.com/edit/angular-ngoffline-npm?file=src%2Fapp%2Fapp.component.html
Works great - BUT I want to open a modal with this ngOffline directive, so I'm trying to access the directive from my angular 11 component but not sure how to approach this, any help on this would be greatly appreciated.
Is there away for me to open a ngx-bootstrap modal from the html with this directive?
Because the ng-offline module isn't exporting things as you might expect (i.e. you can't inject a standalone NgOfflineDirective for you to use without having it in your html file), you could add a block like this (where you've used #trigger to identify your ngOnline element):
import { AfterContentChecked, Component, ElementRef, OnDestroy, ViewChild } from '#angular/core';
import { BehaviorSubject, Subscription } from 'rxjs';
import { distinctUntilChanged, filter } from 'rxjs/operators';
#Component({ ... })
export class YourClass implements AfterContentChecked, OnDestroy {
offline$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>();
subscription: Subscription;
#ViewChild('trigger') trigger: ElementRef;
constructor() {
this.subscription = this.offline$.pipe(
distinctUntilChanged(),
filter((offline: boolean) => offline),
).subscribe(() => this.showModal());
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
ngAfterContentChecked() {
if (
this.trigger &&
this.trigger.nativeElement
) {
this.offline$.next(this.trigger.nativeElement.style.display === "none");
}
}
showModal() {
console.log('Show your modal here.');
}
}
I am trying to make a really simple api call without any logic at all.Althoough I get an illegible object in the consoel called 'proxy' at leaset (not expected either) I cant return anything in the render() method and it throws a typeError.
my code:
Store:
import {observable, configure, action,flow, computed, decorate, set, runInAction} from 'mobx';
import {observer, inject} from 'mobx-react'
configure({enforceActions:'observed'})
class GenStore {
verseData = []
state = "pending"
getVerseData = flow(function*() {
this.verseData = []
this.state = "pending"
try {
const response = yield fetch('https://api.quranwbw.com/2/10')
const data = response.json()
this.state = "done"
this.verseData = data
} catch (error) {
this.state = "error"
}
})
}
decorate(GenStore, {state:observable, verseData: observable, getVerseData:action})
export default new GenStore()
Retrieval:
import {observable, configure, action,flow, computed, decorate, set, runInAction} from 'mobx';
import { computedFn } from "mobx-utils"
import {observer, inject} from 'mobx-react'
import React from 'react'
import GenStore from './GenStore'
class Show extends React.Component{
componentDidMount(){
this.props.GenStore.getVerseData()
}
render(){
console.log(this.props.GenStore.verseData)
return <h1>{this.props.GenStore.verseData.words[0].word_arabic}</h1>
}
}
export default inject('GenStore')(observer(Show))
error returned when i try to render:
TypeError: Cannot read property '0' of undefined
Any help would be appreciated.
Thanx in advance.
Oh, and if you have any suggestion as to how to implement this call if you think flow isnt the choice method, please advise me and tell me how i can do it best
Because getVerseData is async function and when component renders for the first time verseData is an empty array (why it is empty array though? It should be empty object) and respectively verseData.words is undefined.
You can do several things to deal with it, for example, check if verseData.words exists and if not show some loader component instead.
I am getting this error when I try to use rxjs in vue using vue-rx with rxjs.
[Vue warn]: Error in created hook: "TypeError: messageObservable.fromEvent(...).map(...).debounceTime is not a function"
I do not see any wrong imports from the documentation that I looked at and I am not getting any build errors when building the JS on my dev enviroment.
THese are the imports that I have
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
This is the fucntions calling these mehtods.
const messageObservable = Observable;
subscriptions(){
message$: messageObservable
},
created(){
message$.
fromEvent(document.querySelector('textarea'), 'input').
map(event => event.target.value).
debounceTime(500).
distinctUntilChanged().
subscribe({
next: function(value) {
console.log(value);
}
});
},
It seems that the tutorial you are following along is out to date. This imports are not longer working. (see changelog)
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
The latest and stable version is rxjs6. This is the correct way of using it:
import { fromEvent, map, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'
import { Observable } from 'rxjs';
...
created() {
message$.
pipe(
map(event => event.target.value),
debounceTime(500),
distinctUntilChanged()
).subscribe(console.log);
}
I am guessing this is how you want to use fromEvent.
created() {
message$.
pipe(
switchMap(val => fromEvent(document.querySelector('textarea'), 'input'))
map(event => event.target.value),
debounceTime(500),
distinctUntilChanged()
).subscribe(console.log);
}
I see that in Angular 5 one should be using rxjs operators differently and importing from 'rxjs/operators' but I'm a little unclear on how it is supposed to work. I have something like:
import { Observable } from 'rxjs/Observable';
import { combineLatest, takeUntil } from 'rxjs/operators';
#Component({ ... })
export class FooComponent implements OnInit, OnDestroy {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route_data = Observable.combineLatest(this.route.params, this.route.data,
(params, data) => ({params,data}));
this.route_data_sub = this.route_data.takeUntil(this.destroyed$).subscribe(
(params_and_data) => {
...
}
}
...
}
but I'm getting Observable.combineLatest is not a function errors. If I add the combineLatest operator the old way it works for combineLatest, but then takeUntil is now not found. How is this supposed to be done with Angular 5?
I have quite a bit of rxjs code all over the app and don't know how it is supposed to be rewritten or how to change the imports. Does everything have to be rewritten with .pipe() now?
You should import combileLatest use
import { combineLatest } from 'rxjs/observable/combineLatest';
For takeUntil
import { takeUntil } 'rxjs/operators';
I found that information:
combineLatest
takeUntil
#Mad Dandelion has the right answer but I figured it's worth showing what it looks like putting it together for anyone running across the same thing. You do have to pipe things like takeUntil. It's a bit of a pain to go through a large app and find all these spots but doesn't take that long. Doesn't look that bad either and has all the benefits in https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md under "why".
import { Observable } from 'rxjs/Observable';
import { combineLatest } from 'rxjs/observable/combineLatest';
import { takeUntil } from 'rxjs/operators';
#Component({ ... })
export class FooComponent implements OnInit, OnDestroy {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route_data = combineLatest(this.route.params,
this.route.data,
(params, data) => ({params,data})
);
this.route_data_sub = this.route_data
.pipe(takeUntil(this.destroyed$)) //<-- pipe()
.subscribe((params_and_data) => {
...
})
}
...
}
Also in my case I had some stale dlls serving the older rxjs (https://webpack.js.org/plugins/dll-plugin/) so if you run into something that looks like your Observables don't have the pipe property, you might want to make sure the dlls are building properly if you use that.