질문
저는 Angular를 처음 접했으며 현재 "classycountdown "script .이것은 내가 번역하려는 jQuery 함수입니다.
$(document).ready(function() {
var remainingSec = $('.countdown').data('remaining-sec');
$('.countdown').ClassyCountdown({
theme: "flat-colors-very-wide",
end: $.now() + remainingSec
});
});
이것이 사용되는 html입니다.
<div class="countdown"
[attr.data-remaining-sec]="toSec.seconds">
</div>
그리고 이것은 toSec 변수에 대한 component 코드의 일부입니다.
export class AppComponent implements OnInit {
....
toSec = {
seconds: this.scnds
}
}
Angular로 변환하려는 이유는 페이지가 처음로드 될 때 함수가 작동하지 않기 때문입니다. 이는 뷰가 아직로드되지 않았고 다음 문을 통과 할 때 때문이라고 가정합니다. var 잔여 Sec = $ ( '.countdown'). data ( 'remaining-sec'); 첫 번째로드에서 아무것도 찾지 못합니다. 그러나 새로 고침을 누르면 작동이 시작됩니다. 또한 어떤 이유로 localhost에서 테스트 할 때이 문제가 발생하지 않았으며 서버에 배포했을 때만 표시되기 시작했습니다.
모든 입력에 감사드립니다!
답변1
문서 준비 대신 각도 component 수명주기 hook OnAfterViewInit 를 사용하세요. 아마 각도로 다시 쓰려고하지 마십시오. 그것은 거의 이득이없는 큰 일이 될 것입니다.
import $ from "jquery";
export class AppComponent implements OnAfterViewInit {
constructor() {}
ngOnAfterViewInit() {
const remainingSec = $('.countdown').data('remaining-sec');
$('.countdown').ClassyCountdown({
theme: "flat-colors-very-wide",
end: $.now() + remainingSec
});
}
}
답변2
원하는 카운트 다운을 방출하는 관찰 가능 항목을 만듭니다.
timer$ = timer(1000, 1000).pipe(
take(10),
map(val => 10 - val)
);
timer (1000, 1000)는 매초마다 오름차순 숫자를 방출하고 take (10)은 방출하려는 숫자이며 map은 10부터 카운트 다운합니다. 카운트 다운하려는 값을 얻으려면 그것을 가지고 놀 수 있어야합니다.
템플릿에서 비동기 파이프를 사용하여 내 보낸 값을 표시합니다.
{{ timer$ | async }} left to go
다음은 관찰 가능한 타이머의 순수 JS 데모입니다.
const { timer } = rxjs;
const { take, map } = rxjs.operators;
timer(1000, 1000).pipe(
take(10),
map(val => 10 - val)
).subscribe(time => { console.log(time); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js"></script>
출처 : https://stackoverflow.com/questions/63240007/rewrite-jquery-function-to-angular-9