Angular


 
Genelet’s JSON APIs follow a unique URL format. One of the benifits is to write easily the web frontend i.e. View (in MVC) as a single-page HTML5 using Javascript. We demo below our special way to do it in Angular 1.2. You should make better solution using your favored JS Framework. Just FYI, if you run the help command, the samples files will be generated onto disk.

 

URI Mapping

Genelet’s APIs use the format:
http://WEBSITE/HANDLER/role/json/component?action=string&query…     (1)

Your HTML5 page URLs should put role, component, action and query in hash:
http://WEBSITE/#/role/component?action=string&query…                            (2)

 

File Layout

The layout of the HTML5 files is organized in the document root as:

/index.html
/init.js
/genelet.js
/role1/header1.html
/role1/footer1.html
/role1/component1/action1.html
/role1/component1/action2.html
/role1/component2/action1.html
/role1/component2/action2.html

/role2/header2.html
/role2/footer2.html
/role2/login2.html
/role2/component1/action1.html
/role2/component1/action2.html
/role2/component2/action1.html
/role2/component2/action2.html

Here is index.html:

<!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="utf-8">
 <meta name="fragment" content="!" />
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>MYPROJECT</title>
 <script src="/bootstrap/js/jquery.min.js"></script>
 <script src="/bootstrap/js/bootstrap.min.js"></script>
 <script src="/bootstrap/js/angular.min.js"></script>
 <script src="/bootstrap/js/spin.min.js"></script>
 <script src="/init.js"></script>
 <script src="/genelet.js"></script>
 <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
 <style>
 body { padding-top: 50px; }
 .starter-template { padding: 40px 15px; text-align: center; }
 .nav, .pagination, .carousel, .panel-title a { cursor: pointer; }
 </style>
 </head>
 <body ng-app="app_wavelet" ng-controller="body_wavelet">
 
 <ng-include src="partial_header"></ng-include>
 
 <div class="container">
 <span id="spinner"></span>
 <ng-include src="partial"></ng-include>
 </div>
 
 <ng-include src="partial_footer"></ng-include>
 
 </body>
 </html>

Here we use Bootstrap as the CSS framework and the spin plugin spin.js for page-loading indicator.

Here is init.js that defines a global variable called GOTO:

var GOTO = {
script: Your API_SCRIPT_NAME,
role: Default ROLE_NAME if not in URL,
component: Default COMPONENT_NAME if not in URL,
action: Default ACTION_NAME if not in URL,
type: "html",
json: "json",
header: "header",
footer: "footer",
login: "login",
modals: [MODAL_NAME1, MODAL_NAME2, ...]
}

The program genelet.js (download here) will call the serve API in (1) and retrieve data to fill in the Angular template, at every time when the URL is refreshed.  The JSON data are saved in variable called names. Since verbs edit, insert and update usually contain only one item in names‘ array, we copy it to a separately variable called single. Developer can use names and single to display any dynamical content according to the HTML5 templates.

For each role, you can attach its own header and footer. For testing purpose you may leave them as two empty files.

In the above example,  we assume role1 is a public role so there is no login file associated. And role2 is a protected role whose visitors have to login first using a login form. Here is example login2.html:

<h3>{{ names.errorstr }}</h3>
<FORM name=admin_login ng-init="data.role='admin';data.tag='json';data.direct=1" ng-submit="$parent.login('admin','db',data,{role:'admin', component:'site',action:'topics'})">
<pre>
Username: <INPUT TYPE="TEXT" ng-model="data.login" />
Password: <INPUT TYPE="PASSWORD" ng-model="data.passwd" />
<INPUT TYPE="SUBMIT" value=" Log In " />
</pre>
</FORM>

 

Anchor Links

Anchor link uses the format:

<a href=”” ng-click=”go(role, component, action, query, landing)”></a>     (3)

Clicking on the link will result in the browser to navigate, depending on how landing is passed in:

  • landing is null, it simulates the traditional anchor, i.e. jump to new page:
    http://WEBSITE/#/role/component?action=string&query
  • landing is string, it retrieves the API data only. No anchor jump nor page refresh. The returned data are saved in object string, instead of overriding the existing data array names. A variety of the function called optional_go is also available. If the name object string is already existing, the API call will simply be ignored. The use case of this landing is when you want two or more API data on one page.
  • landing == {operator: stringid_name: string} where operator string is one of insert, update or delete. No anchor jump. This landing is used to change the existing lists on spot, without refreshing the page. The optional variable  id_name defines the primary key in delete or update. The use case is when you want to insert, delete or update dynamic data without refreshing the current page.
  • landing == {role: stringcomponent: string, action: string, query: object}. After running the original API, it will redirect to the new URL while running the following, second API:
    /#/landing{role}/landing{component}?action=string&landing{query}
    For example, after a user updates his credit card, you lead her back to the original payment page. You need two API calls for this click: (1) update her credit card and (2) refresh the payment page, presumably with the updated card information on it.

 

POST a Form

To make a POST request, e.g. to submit a form, we use:

send(role, component, action, query, landing)

All the parameters and use cases are the same as the above GET anchor.

 

Login

While the login process is also a POST, we’d like an easier API:

login(role, provider, query,  landing)

where provider is the name of the authentication agent. landing is {role: string, component: string, action: string, query: object}. After the successful login to role, the URL will be redirected to what defined in landing.

 

561 thoughts to “Angular”

  1. Попробовав новую службу заказа такси и трансфера, я остался приятно удивлен ее производительностью и удобством. Мобильное приложение позволяет быстро и легко вызвать автомобиль, указав аккуратное местоположение и время прибытия. Я заказывал такси по маршруту http://kubtaxi.ru/transfer/taxi-simferopol-semidvore
    . Водители прибывают вовремя, а степень автомобилей оставляет приятное впечатление. Кроме того, система оценок и обратной связи о водителях помогает выбирать наиболее верных исполнителей. Я также оценил комфорт оплаты через приложение, что делает процедуру заказа и расчета максимально простым и безопасным. В целом, новейшая служба заказа такси и трансфера обосновала мои ожидания и стала неотъемлемым помощником в моих перемещениях по городу.

  2. [url=https://infinitymassagechairs.org/]massage chair for sale[/url]:
    Looking for a massage chair for sale? Look no further than InfinityMassageChairs.org. We offer a wide range of high-quality massage chairs at competitive prices. Our massage chairs are designed to provide exceptional comfort and therapeutic benefits, allowing you to experience the ultimate relaxation in the comfort of your own home. With our massage chairs, you can enjoy the convenience of a professional-quality massage anytime you desire. Explore our collection of massage chairs for sale and take the first step towards enhancing your well-being.

    4. Infinity Massage Chair:
    At InfinityMassageChairs.org, we are proud to offer the Infinity Massage Chair collection. Our Infinity line combines innovative technology with superior craftsmanship to deliver an unparalleled massage experience. With features like zero gravity positioning, advanced body scanning, and customizable massage programs, Infinity Massage Chairs provide a truly indulgent and therapeutic experience. Discover the benefits of owning an Infinity Massage Chair and elevate your relaxation routine to new heights.

    5. [url=https://infinitymassagechairs.org/]best Massage chair for sale[/url]:
    Searching for the best massage chair? Look no further than InfinityMassageChairs.org. We are dedicated to providing top-quality massage chairs that prioritize your well-being. Our carefully curated selection of massage chairs offers unrivaled comfort, advanced features, and customizable massage options. Whether you’re seeking relief from muscle tension or simply want to unwind after a long day, our best massage chairs are designed to meet your specific needs. Experience the ultimate in relaxation and invest in the best massage chair for your home.

  3. Как чёрный брокер Esperio маскируется под нормального

    Отзывы о «Эсперио»
    Многие лохоброкеры легко меняют названия и доменные имена своих проектов. Однако этот за название цепляется вот уже скоро год, даже несколько зеркал последовательно запустил, после блокировок за мошенничество.

    Причина такой приверженности к названию становится понятна, если поискать отзывы о Esperio. Организаторы лохотрона потратились на изрядное количество платных комментариев, причём в две волны. Первую к запуску лжеброкера летом 2021 года, вторую — на рубеже 2021 и 2022 года. Не пропадать же добру из-за того, что по предписанию Центробанка сайт блокируют за попытку предлагать нелегальные финансовые услуги: всё-таки потратились на написание и размещение на множестве площадок. Эти площадки, правда, выбирали по принципу побольше и подешевле, лишь бы занять места в топе выдачи запросов. Особенно размещение на портале «Брянские новости» доставляет.

    Реальные отзывы о Esperio также встречаются: показываем образцы на скриншоте. Жертвы лжеброкеров дружно жалуются на невозможность вывести деньги.

    Как чёрный брокер Esperio маскируется под нормального

    Схема развода «Эсперио»
    Здесь всё стандартно. Выводить сделки на межбанк анонимный лохотрон не может. Трейдинг здесь в лучшем случае имитируют с помощью поддельных терминалов, выдавая учебные симуляторы за реальную торговлю. Лжеброкер работает исключительно на приём средств, непрерывно уговаривая жертв нарастить депозиты под любыми предлогами. Вывод денег из Esperio выполнить не позволят. Разве что некоторым клиентам, которых мошенники признали особо перспективными, позволяли снять тестовую мелочь. Исключительно успокаивая бдительность и выманивая крупные суммы, с которыми аферисты уже не расстанутся.

    Заключение
    Лжеброкер Esperio потратился на приличный нешаблонный сайт и платные отзывы. Значит, пришёл разводить людей всерьёз и надолго. Такие мошенники опаснее топорно выполненных однодневок, однако изучение их базовой юридической информации позволяет своевременно опознать лохотрон.

  4. Amcv.ro – Strategii de promovare eficiente – Platforma unde creativitatea si promovarea se intalnesc pentru a da viata afacerilor tale!
    Ne-am propus sa oferim o platforma unica si eficienta pentru cei interesati sa-si promoveze afacerile, produsele sau serviciile prin intermediul advertorialelor personalizate si a articolelor de promovare. Suntem aici pentru a va ajuta sa va faceti vocea auzita in lumea online, sa va conectati cu audienta tinta si sa va evidentiati in fata competitorilor.
    Indiferent daca aveti o afacere mica sau una mai mare, Amcv.ro este locul potrivit pentru a va face cunoscut mesajul. Cu noi, puteti posta advertoriale personalizate care sa reflecte in mod autentic valorile si misiunea afacerii dumneavoastra. Fie ca sunteti in domeniul comertului, al serviciilor sau al productiei, exista mereu un spatiu pentru dumneavoastra pe Amcv.ro.

  5. ####### OPVA ########
    ULTIMATE РТНС COLLECTION
    NO PAY, PREMIUM or PAYLINK
    DOWNLOAD ALL СР FOR FREE

    Description:-> tiny.cc/zd48vz

    Webcams РТНС since 1999 FULL
    STICKAM, Skype, video_mail_ru
    Omegle, Vichatter, Interia_pl
    BlogTV, Online_ru, murclub_ru

    Complete series LS, BD, YWM
    Sibirian Mouse, St. Peterburg
    Moscow, Liluplanet, Kids Box
    Fattman, Falkovideo, Bibigon
    Paradise Birds, GoldbergVideo
    Fantasia Models, Cat Goddess
    Valya and Irisa, Tropical Cuties
    Deadpixel, PZ-magazine, BabyJ
    Home Made Model (HMM)

    Gay рthс collection: Luto
    Blue Orchid, PJK, KDV, RBV

    Nudism: Naturism in Russia
    Helios Natura, Holy Nature
    Naturist Freedom, Eurovid

    ALL studio collection: from
    Acrobatic Nymрhеts to Your
    Lоlitаs (more 100 studios)

    Collection european, asian,
    latin and ebony girls (all
    the Internet video) > 4Tb

    Rurikon Lоli library 171.4Gb
    manga, game, anime, 3D

    This and much more here:
    or –> tw.uy/tlvic
    or –> citly.me/Qdw8X
    or –> u2b.eu/ua
    or –> tt.vg/fiJTt
    or –> thr.fi/NYwpwdx6
    or –> me2.kr/KBMgQ
    or –> gg.gg/18ek6k
    or –> gurl.pro/w-0i6v
    or –> u2b.eu/zn
    —————–
    —————–
    000A000141

  6. Хотите разнообразить свой опыт на BongaCams? Не хватает токенов или хочется приобрести аккаунт с дополнительными привилегиями? Мы предлагаем широкий выбор токенов и аккаунтов BongaCams по самым привлекательным ценам. Наш сервис гарантирует безопасность и конфиденциальность вашей покупки. Получите доступ к эксклюзивным возможностям BongaCams прямо сейчас, сделав выгодную покупку у нас!
    bongacams купить токены

  7. Регистрация в букмекерской конторе BetBoom открывает перед вами увлекательный мир спортивных ставок и возможность заработка на удаче и знании спорта. Процесс регистрации на официальном сайте BetBoom прост и удобен: вам нужно заполнить всего несколько обязательных полей, подтвердить свои данные и выбрать удобный способ пополнения счета. Подробная инструкция – https://t.me/s/registraciya_betboom_ru

Leave a Reply

Your email address will not be published. Required fields are marked *